无子查询的条件左连接MySQL

时间:2018-02-13 13:15:04

标签: mysql sql database left-join

我有两张桌子,X和Y:

mysql> select * from X;
+------+------+
| id   | colX |
+------+------+
| 2001 |    0 |
| 2002 |    0 |
| 2003 |    0 |
| 2004 |    0 |
| 2005 |    0 |
| 2006 |   10 |
| 2007 |   10 |
+------+------+

mysql> SELECT * FROM Y;
+------+------+-------+
| id   | colY | score |
+------+------+-------+
| 2001 |   10 |     3 |
| 2004 |    0 |    12 |
| 2005 |    0 |    15 |
| 2007 |    0 |     1 |
+------+------+-------+

我需要以下结果,但没有子查询:

mysql> SELECT * FROM X LEFT JOIN Y ON X.id = Y.id WHERE colX=0 AND X.id NOT IN (SELECT id FROM Y WHERE colY > 0);
+------+------+------+------+-------+
| id   | colX | id   | colY | score |
+------+------+------+------+-------+
| 2002 |    0 | NULL | NULL |  NULL |
| 2003 |    0 | NULL | NULL |  NULL |
| 2004 |    0 | 2004 |    0 |    12 |
| 2005 |    0 | 2005 |    0 |    15 |
+------+------+------+------+-------+
  • colX必须为0
  • 如果表Y中存在id且colY = 0则给出相应的分数
  • 如果表Y中没有id,则给出分数= NULL

我尝试了以下查询但是id 2001显示:

mysql> SELECT * FROM X LEFT JOIN Y ON X.id = Y.id AND Y.colY = 0 WHERE colX=0;
+------+------+------+------+-------+
| id   | colX | id   | colY | score |
+------+------+------+------+-------+
| 2001 |    0 | NULL | NULL |  NULL |
| 2002 |    0 | NULL | NULL |  NULL |
| 2003 |    0 | NULL | NULL |  NULL |
| 2004 |    0 | 2004 |    0 |    12 |
| 2005 |    0 | 2005 |    0 |    15 |
+------+------+------+------+-------+

1 个答案:

答案 0 :(得分:6)

我认为这是你想要的逻辑:

h264_nvenc

Demo