1. 程式人生 > >MySQL-連線查詢

MySQL-連線查詢

  1. 連線查詢
  • –內連線查詢

    JOIN|CROSS JOIN|INNER JOIN 通過ON連線條件,顯示兩個表中符合連線條件的記錄
    
  • –外連線查詢

    左外連線 LEFT [OUTER] JOIN 顯示左表的全部記錄及右表符合連線條件的記錄
    右外連線 RIGHT [OUTER] JOIN 顯示右表的全部記錄以及左表符合條件的記錄
    
  1. 內連線查詢練習
  • –查詢使用者表中的編號,使用者名稱,省份表中的省份名字
SELECT id,username,proName FROM cms_user,provinces;		#錯誤
SELECT cms_user.id,username,proName FROM cms_user,provinces;	#指定表名
  • –使用者表cms_user中的proId對應省份表provinces中的id
SELECT cms_user.id,username,proName FROM cms_user,provinces WHERE cms_user.proId=provinces.id;
  • –查詢cms_user表中的id,username,email,sex,查詢provinces表中的proName
SELECT a.id,a.username,a.email,a.sex,b.proName 
FROM cms_user AS a
INNER JOIN provices AS b
ON a.proId=b.id;

SELECT a.id,a.username,a.email,a.sex,b.proName 
FROM provinces AS b
CROSS JOIN cms_user AS a
ON a.proId=b.id;
  • –INNER|CROSS可省略
SELECT a.id,a.username,a.email,a.sex,b.proName 
FROM provinces AS b
JOIN cms_user AS a
ON a.proId=b.id;
  • –查詢cms_user表中的 id,username,sex,查詢provinces表中的 proName,條件是cms_user中性別為男的使用者
SELECT a.id,a.username,a.sex,b.proName
FROM cms_user AS a
JOIN provinces AS b
ON a.proId=b.id
WHERE u.sex='男';
  • –再根據proName分組
SELECT a.id,a.username,a.sex,b.proName,COUNT(*) AS totalUsers
FROM cms_user AS a
JOIN provinces AS b
ON a.proId=b.id
WHERE u.sex='男'
GROUP BY b.proName;
  • –再對分組結果進行二次篩選,選出組中人數大於等於1的記錄
SELECT a.id,a.username,a.sex,b.proName,COUNT(*) AS totalUsers,GROUP_CONCAT(username)
FROM cms_user AS a
JOIN provinces AS b
ON a.proId=b.id
WHERE u.sex='男'
GROUP BY b.proName
HAVING COUNT(*) >=1;
  • –再按照id升序排序
SELECT a.id,a.username,a.sex,b.proName,COUNT(*) AS totalUsers,GROUP_CONCAT(username)
FROM cms_user AS a
JOIN provinces AS b
ON a.proId=b.id
WHERE u.sex='男'
GROUP BY b.proName
HAVING COUNT(*) >=1
ORDER BY a.id ASC;
  • –查詢cms_news中的id,title,查詢cms_cate中的cateName
SELECT a.id,a.title,b.cateName 
FROM cms_news AS a
JOIN cms_cate AS b
ON a.cId=b.id;
  • –查詢cms_news中的id,title,查詢cms_admin中的username,role
SELECT a.id,a.title,b.username,b.role 
FROM cms_news AS a
JOIN cms_admin AS b
ON a.aId=b.id;
  • –三表聯查;查詢cms_news中的id,title,查詢cms_cate中的cateName,查詢cms_admin中的username,role
SELECT n.id,n.title,c.cateName,a.username,a.role
FROM cms_news AS n
JOIN cms_cate AS c
ON n.cId=c.id
JOIN cms_admin AS a
ON n.aId=a.id;
  1. 外連線查詢練習
  • –左外連線(以左表為主表)
SELECT a.id,a.username,a.email,a.sex,b.proName 
FROM cms_user AS a
LEFT JOIN provices AS b
ON a.proId=b.id;
  • –右外連線(以右表為主表)
SELECT a.id,a.username,a.email,a.sex,b.proName 
FROM provices AS b
RIGHT JOIN cms_user AS a
ON a.proId=b.id;