$sql = "select * from article where id=1";
-- 等同於
$sql = "select * from article
where id=1";
長 SQL 分行更清晰。
$sql = "select * from article where id in(1,3,5)";
$sql = "select concat(id,'-',con) as res from article where id=1";
-- 返回 "1-article content"
SELECT LOCATE("hello", "hello baby"); -- 返回 1
-- 不存在返回 0
GROUP BY 將相同值分組,常搭配 AVG()、MIN()、MAX()、SUM()、COUNT()。
$sql = "select city, count(*) from customer group by city";
-- 列出所有不重複城市及其數量 (類似 DISTINCT 但帶統計)
$sql = "select city, count(*), min(birth_day) from customer
group by city having count(*) > 10";
-- 先按 city 分組,再找出數量 > 10 的城市
注意:GROUP BY + HAVING 較慢;HAVING 中表達式必須在 SELECT 列表中出現過。
WHERE → GROUP BY → HAVING → ORDER BY(四者共用時按此序)
$sql = "select distinct city from customer order by id desc";
-- 查詢所有不重複 city
$sql = "select * from article limit 100, -1";
-- 顯示第 100 條之後所有記錄
$sql = "select user_name from user u, member m
where u.id = m.id and m.reg_date >= '2006-12-28'
order by u.id desc";
關鍵: 若兩表同有 user_name 欄位,必須指明屬哪表(如 u.user_name),否則 MySQL 報錯。