mysql> SELECT * FROM users GROUP BY password;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 3 | moon1 | 123456 |
| 1 | moon | 456789 |
+----+----------+----------+
2 rows in set (0.01 sec)
mysql> SELECT * FROM users GROUP BY username;
+----+----------+----------+
| id | username | password |
+----+----------+----------+
| 2 | alex1 | 456789 |
| 1 | moon | 456789 |
| 3 | moon1 | 123456 |
+----+----------+----------+
3 rows in set (0.01 sec)
使用 LIMIT 限制查询结果的数量
select * from users limit 2,10;
select * from users as u where u.id=1;
为表和字段取别名
select username as myname from users;
2.mysql的子查询
where型子查询
(把内层查询结果当作外层查询的比较条件)
select * from users where id in (select id from users where id>10);
from型子查询
(把内层的查询结果供外层再次查询)
select * from (select username,age from users) as agev_a where age>20
select * from (select * from users where id>=10) as age_10;
(select * from users where id>=10)查询出来的是一个集合 别名为age_10
select * from age_10
exists型子查询
(把外层查询结果拿到内层,看内层的查询是否成立)
1
0
select * from users where EXISTS (select * from users where id>1)
联合查询(两个表的查询)
注释:默认地,UNION 操作符选取不同的值。如果允许重复的值,请使用 UNION ALL。 当 ALL 随 UNION 一起使用时(即 UNION ALL),不消除重复行
UNION ALL 查询全部 而且不会消除重复的行 union
SQL UNION ALL 语法
union的用法及注意事项 两次查询的列数必须一致
select * from users union select *,1 from news;
CREATE TABLE `news` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`title` varchar(255) not NULL,
`content` varchar(255) not null,
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=0 DEFAULT CHARSET=utf8;
insert into news (title,content)values('a1','a1');