SELECT xxx AS xxxx FROM WHERE GROUP BY HAVING
SELECT column_name(s) FROM table_name AS alias_name
-- JOIN: 若是表中有至少一個匹配,則返回行; 和INNRE JION 相同 SELECT column_name(s) FROM table_name1 INNER JOIN table_name2 ON table_name1.column_name=table_name2.column_name -- LEFT JOIN: 即便右表中沒有匹配,也從左表返回全部的行;會返回左表(table1)中全部的行 SELECT column_name(s) FROM table_name1 LEFT JOIN table_name2 ON table_name1.column_name=table_name2.column_name -- RIGHT JOIN: 即便左表中沒有匹配,也從右表返回全部的行 SELECT column_name(s) FROM table_name1 RIGHT JOIN table_name2 ON table_name1.column_name=table_name2.column_name -- FULL JOIN: 只要其中一個表中存在匹配,就返回行; 會從左右表中返回全部的行,無論左右匹不匹配 SELECT column_name(s) FROM table_name1 FULL JOIN table_name2 ON table_name1.column_name=table_name2.column_name -- CROSS JOIN: 會把左右表個列相乘,返回N*M 的組合
用菜鳥教程裏的幾張圖形象的表示出來html
+-------------+---------+ | 列名 | 類型 | +-------------+---------+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +-------------+---------+
PersonId 是上表主鍵mysql
表2: Addresssql
+-------------+---------+ | 列名 | 類型 | +-------------+---------+ | AddressId | int | | PersonId | int | | City | varchar | | State | varchar | +-------------+---------+
AddressId 是上表主鍵數據庫
編寫一個 SQL 查詢,知足條件:不管 person 是否有地址信息,都須要基於上述兩表提供 person 的如下信息:FirstName, LastName, City, State學習
-- 建立表 CREATE TABLE person( PersonID int PRIMARY KEY, FirstName varchar(20), SecondName varchar(20) ); INSERT INTO person VALUES(1,'Gali','Ma'); INSERT INTO person VALUES(2,'Yao','Xiao'); INSERT INTO person VALUES(3,'Tao','Baiwan'); CREATE TABLE address( AddressId int PRIMARY KEY, PersonId int, City varchar(20), State varchar(20) ); INSERT INTO address VALUES(1,2,'Huangpu','Shanghai'); INSERT INTO address VALUES(2,1,'Huangpu','Shanghai'); INSERT INTO address VALUES(3,3,'Changsha','Hunan'); INSERT INTO address VALUES(4,4,'Haidian','Beijing'); SELECT Person.FirstName, Person.SecondName, Address.City,Address.State FROM Person LEFT JOIN Address ON Person.PersonID = Address.PersonId
結果:code
+----+---------+ | Id | Email | +----+---------+ | 1 | a@b.com | | 2 | c@d.com | | 3 | a@b.com | +----+---------+
Id 是這個表的主鍵。
例如,在運行你的查詢語句以後,上面的 Email表應返回如下幾行:htm
+----+------------------+ | Id | Email | +----+------------------+ | 1 | a@b.com | | 2 | c@d.com | +----+------------------+
解答:blog
DELETE FROM email WHERE Id NOT IN ( SELECT minId FROM ( SELECT MIN(Id) as minId FROM email GROUP BY Email ) table_tmp ); SELECT * FROM email;
My SQL 不能直接刪除 You can't specify target table 'table name' for update in FROM clause; 因此須要加一個臨時表,還須要給臨時表和列起別名。教程
結果:ci