MySQL中的INNER JOIN

时间:2015-11-29 13:28:52

标签: mysql sql

有两张桌子:

表名: 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      |
+-------+---------+---------+-------------------+

表名: ORDERS

+-------+---------+---------+-----------------+
|  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 个答案:

答案 0 :(得分:3)

您不应在firstName中使用ORDERS作为外键。外键应该引用主键。使用ID中的FRIENDS,例如:

表名: ORDERS

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

使用LEFT OUTER JOIN进行查询:

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)
  ...
);