我有两张桌子正在尝试合并。我想要显示所有EmbroideryID的左表,而右表应该为那些EmbroideryID返回null。但是,我只得到两张表中都存在的EmbroideryID,这不是我想要的。我想要左表中的所有结果,无论我的右表是否有结果。
左表:
mysql> SELECT * FROM Embroidery WHERE Customer = 'AAAAAAAA';
+--------------+----------+--------------------------+
| EmbroideryID | Customer | Description |
+--------------+----------+--------------------------+
| 1 | AAAAAAAA | Embroidery1 |
| 2 | AAAAAAAA | Embroidery2 |
| 3 | AAAAAAAA | Embroidery3 |
| 4 | AAAAAAAA | Embroidery4 |
| 5 | AAAAAAAA | Embroidery5 |
+--------------+----------+--------------------------+
右表:
SELECT * FROM EmbroideryForMen;
+----------+--------------+-----------+
| Customer | EmbroideryID | ManNumber |
+----------+--------------+-----------+
| AAAAAAAA | 1 | 4 |
| AAAAAAAA | 1 | 8 |
| AAAAAAAA | 1 | 12 |
+----------+--------------+-----------+
我期待的是:
+--------------+----------+--------------------------+-----------+
| EmbroideryID | Customer | Description | ManNumber |
+--------------+----------+--------------------------+-----------+
| 1 | AAAAAAAA | Embroidery1 | 4 |
| 1 | AAAAAAAA | Embroidery2 | 8 |
| 1 | AAAAAAAA | Embroidery3 | 12 |
| 2 | AAAAAAAA | Embroidery4 | NULL |
| 3 | AAAAAAAA | Embroidery5 | NULL |
| 4 | AAAAAAAA | Embroidery5 | NULL |
| 5 | AAAAAAAA | Embroidery5 | NULL |
+--------------+----------+--------------------------+-----------+
以下是您可以查看的SQLFiddle:http://sqlfiddle.com/#!2/579bac/3
我想要看到这样的表的原因是因为并非所有时间用户都会选择一个人来接收刺绣,因此永远不会创建行/记录。我想避免将空记录写入EmbroideryForMen,但如果需要,我会这样做。
非常感谢任何帮助。
答案 0 :(得分:1)
以下是如何实现目标:
将m.customer = "AAAAAAAA"
替换为e.customer = "AAAAAAAA"
(因为m.customer可以为null且为null!=“AAAAAAAA”)和
删除AND e.EmbroideryID = 1
(显示所有行)
SELECT *
FROM Embroidery e
LEFT JOIN EmbroideryForMen m
ON e.EmbroideryID = m.EmbroideryID
AND e.Customer = m.Customer
WHERE e.Customer = "AAAAAAAA";
答案 1 :(得分:1)
执行left join
时, second 表中的条件应该放在on
子句中。否则,值为NULL
,并且将在where
子句中的大多数比较失败。第一个表的条件应该放在where
子句中,否则它们没有效果。
因此,您想要的查询是:
SELECT *
FROM Embroidery e LEFT JOIN
EmbroideryForMen m
ON e.EmbroideryID = m.EmbroideryID AND
e.Customer = m.Customer AND
m.Customer = "AAAAAAAA" AND
m.EmbroideryID = 1;