我正在尝试加入两张桌子,只选择没有在任何订单上使用促销代码的经销商。
我该怎么做?
我在下面尝试此操作,但它无法正常工作。在示例中,我想得到Bob,因为他的promo_code
还没有被用于任何订单。
SELECT d.`name`
FROM z_dealer d
LEFT OUTER JOIN z_order o ON (d.promo_code = o.promo_code)
AND o.promo_code IS NULL
这是我的表......
mysql> select * from z_dealer;
+----+------+------------+
| id | name | promo_code |
+----+------+------------+
| 1 | John | holiday |
| 2 | Suzy | special |
| 3 | Bob | laborday |
+----+------+------------+
mysql> Select * from z_order;
+----+-------+------------+
| id | total | promo_code |
+----+-------+------------+
| 1 | 10 | holiday |
| 2 | 20 | special |
| 3 | 15 | holiday |
| 4 | 45 | special |
+----+-------+------------+
答案 0 :(得分:1)
SELECT d.`name` FROM z_dealer d LEFT JOIN z_order o ON (d.promo_code = o.promo_code) WHERE o.promo_code IS NULL
答案 1 :(得分:0)
你试过INNER JOIN
吗?或者您可以尝试这样IN
:
SELECT d.name
FROM z_dealer d
WHERE d.promo_code not in( SELECT promo_code FROM z_order)
答案 2 :(得分:0)
我不完全确定为什么它不适用于您的示例代码。我在本地创建了相同的表,当我运行你提供的脚本时,我得到了单个“Bob”的答案。
SELECT d.name
FROM z_dealer d
LEFT OUTER JOIN z_order o ON (d.promo_code = o.promo_code)
AND o.promo_code IS NULL
您到底看到了什么结果?