SELECT
column_1, column_2, ...
FROM
table_1
[INNER | LEFT |RIGHT] JOIN table_2 ON conditions
WHERE
conditions
GROUP BY column_1
WITH ROLLUP
HAVING group_conditions
LIMIT offset, length;
JOIN测试:
SELECT a.user_id FROM usertable a JOIN testtable b ON a.username = b.username;
等同于:用where
SELECT a.user_id FROM usertable a, testtable b WHERE a.username = b.username;
LEFT JOIN测试:MySQL LEFT JOIN 会读取左边数据表的全部数据,即便右边表无对应数据。
在使用left jion时,on和where条件的区别如下:
1、 on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。
2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉
SELECT a.user_id ,a.username,b.score FROM usertable a LEFT JOIN testtable b ON a.username = b.username;
SELECT field1, field2,...fieldN FROM table_name1, table_name2...
[WHERE condition1 [AND [OR]] condition2.....
SELECT column_name, function(column_name)
FROM table_name
WHERE column_name operator value
GROUP BY column_name;
SELECT username FROM usertable GROUP BY age;
SELECT username,COUNT(*) FROM usertable GROUP BY age;
Select username,age from usertable having age>25 AND username!='Joy';
但是
Select username from usertable having age>25 AND username!='Joy';
会报错Unknown column 'age' in 'having clause'
说明条件字段必须在查询的字段中
但是where就不用
和where
Select username,age from usertable where age>25 AND username!='Joy';
Select username from usertable where age>25 AND username!='Joy';#不会报错;
where和having的区别
请注意,HAVING子句将过滤条件应用于每组分行,而WHERE子句将过滤条件应用于每个单独的行。
SELECT field1, field2,...fieldN table_name1, table_name2...
ORDER BY field1, [field2...] [ASC [DESC]]
升序排列按年龄大小
SELECT username,age FROM usertable ORDER BY age ASC;
SELECT...[LIMIT offset_start,row_count]
offset_start 是其实偏移量,row_count 是显示的行数
Select username from usertable where age>ANY(SELECT age from usertable);
Select username from usertable where age>=ALL(SELECT age from usertable);
Select username from usertable where age<=ALL(SELECT age from usertable);
用于子查询的关键字包括:in、not in、=、!=、exits、not exists等。