mysql語句的語法模板:
select distinct <select_list>
from
<left_table><join_type> join <right_table> on <join_condition>
where <where_condition>
group by <group_by_rowname>
having <having_condition>
order by <order_by_condition>
limit <limit_number>
mysql的執行順序如圖:
mytest表 如圖:

想先根據department字段分組,在按照price字段排序:SELECT * FROM mytest ORDER BY department ,price
想查詢每個department字段的最大price值時:SELECT id ,department,MAX(price) FROM mytest GROUP BY department
多表關聯查詢時,表結構如圖:
user表

pay 表

spay表:

其中pay表 是用戶繳費表,spay表 是應該繳費表
想要查詢用戶欠費的記錄時查詢如下:
SELECT spay.userId, (T.mypay-spay.shouldPay) AS own FROM
(SELECT userId,SUM(mypay) AS mypay FROM pay GROUP BY userId) AS T LEFT JOIN spay ON spay.`userId`=T.userId
注意:有時候需要用到關鍵字union關鍵字,union是合並+去重的操作
