我有两个表,我试图结合。左边的表格我期望显示所有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,但如果需要,我会去做。
任何帮助,非常感谢。
你'WHERE'条款应限制在左表的列('e'),而不是右左连接表('M' ),当然,删除embroideryid上的限制:[fiddle](http://sqlfiddle.com/#!2/579bac/10)。重要的是要记住的是:'LEFT JOIN'ed表中的列全部为NULL,所以不要在'WHERE'子句中检查它们,除非明确地_want_检查不存在。 – Wrikken 2014-12-04 20:52:56