2015-11-29 213 views
0

有我的兩個表:INNER JOIN在MySQL

表名:FRIENDS

+-------+---------+---------+-------------------+ 
| id | firstName | lastName | city  | 
+-------+--------------+------------+-----------+ 
| 1  | dudi   | edri  | london | 
| 2  | maor   | azulay  | madrid | 
| 3  | batel  | azulay  | tel aviv | 
| 4  | nir   | cohen  | barcelona | 
| 5  | evia   | perez  | miami  | 
| 6  | neria  | perez  | new-york | 
| 7  | nevo   | kakoun  | roma  | 
+-------+---------+---------+-------------------+ 

表名:訂單

+-------+---------+---------+-----------------+ 
| id | firstName | amount | status | 
+-------+--------------+----------+-----------+ 
| 1  | dudi   | 5684  | shipped | 
| 2  | maor   | 4896  | shipped | 
| 3  | batel  | 2496  | delay  | 
+-------+--------------+----------+-----------+ 

我的問題是: 我想沒有訂單的朋友。 答案:

| 4  | nir   | cohen  | barcelona | 
| 5  | evia   | perez  | miami  | 
| 6  | neria  | perez  | new-york | 
| 7  | nevo   | kakoun  | roma  | 
+-------+---------+---------+-------------------+ 

我怎麼寫的查詢與內部聯接。 謝謝。

+1

你不應該在'ORDERS'爲外鍵使用您的名字。沒有任何意義 – lad2025

+0

是 - 外鍵應該引用主鍵 – Strawberry

+0

要做內連接的列是:id –

回答

3

您不應該在ORDERS中使用firstName作爲外鍵。外鍵應引用主鍵。使用LEFT OUTER JOIN訂單

+-------+---------+---------+-----------------+ 
| id | friendID | amount | status | 
+-------+--------------+----------+-----------+ 
| 1  | 1   | 5684  | shipped | 
| 2  | 2   | 4896  | shipped | 
| 3  | 3   | 2496  | delay  | 
+-------+--------------+----------+-----------+ 

和查詢:使用IDFRIENDS,如:

表名

SELECT f.* 
FROM FRIENDS f 
LEFT JOIN ORDERS o 
    ON f.ID = o.friendID 
WHERE o.ID IS NULL; 

LiveDemo

另一種可能性是使用correlated subquery

SELECT f.* 
FROM FRIENDS f 
WHERE NOT EXISTS (SELECT 1 
        FROM orders o 
        WHERE o.friendID = f.ID); 

LiveDemo2


表:

CREATE TABLE friends(
    id  INTEGER NOT NULL PRIMARY KEY  -- you can add AUTO_INCREMENT if needed 
    ... 
); 

CREATE TABLE orders(
    id  INTEGER NOT NULL PRIMARY KEY  
    ,friendID INTEGER NOT NULL 
    ,FOREIGN KEY (friendID) REFERENCES friends(id) 
    ... 
);