我有 2 个表
+------------+-----------+-----------+
| itemid | version | anything |
+------------+-----------+-----------+
| foo | v0 | blah |
| foo | v1 | blah |
| foo | NULL | blah |
| foo | v2 | meh |
| bar | v0 | meh |
| bar | v1 | 24 |
| baz | NULL | 25 |
| qux | NULL | 26 |
+------------+-----------+-----------+
和
+------------+-----------+-----------+
| itemid | version | something |
+------------+-----------+-----------+
| foo | v0 | weck |
| foo | NULL | wock |
| foo | v2 | weck |
| bar | v0 | meck |
| bar | v1 | cuack |
| baz | NULL | crack |
| qux | NULL | blah |
+------------+-----------+-----------+
我需要通过 itemid
和 version
连接两个表,因此结果如下所示:
+------------+-----------+-----------+-----------+
| itemid | version | anything | something |
+------------+-----------+-----------+-----------+
| foo | v0 | blah | weck |
| foo | v1 | blah | NULL |
| foo | NULL | blah | wock |
| foo | v2 | meh | weck |
| bar | v0 | meh | meck |
| bar | v1 | 24 | cuack |
| baz | NULL | 25 | crack |
| qux | NULL | 26 | blah |
+------------+-----------+-----------+-----------+
我在做
SELECT t1.itemid,
t1.version,
t1.anything,
t2.something
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.itemid=t2itemid AND t1.version=t2.version
它处理具有版本值的行,但如果版本值NULL
则具有 null 值的行如下所示:
+------------+-----------+-----------+-----------+
| itemid | version | anything | something |
+------------+-----------+-----------+-----------+
| foo | NULL | blah | NULL |
| baz | NULL | 25 | NULL |
| qux | NULL | 26 | NULL |
+------------+-----------+-----------+-----------+
我尝试使用以下命令更改连接条件:
ON t1.itemid=t2.itemid AND (t1.version=t2.version OR ((t1.version is null) AND (t2.version is null)))
结果完全相同
我也尝试通过以下方式更改条件:
ON t1.itemid=t2.itemid AND (t1.version=t2.version OR ((isnull(t1.version,'-')) AND (isnull(t1.version,'-'))))
然后我得到错误:An expression of non-boolean type specified in a context where a condition is expected,near 'AND' [SQL State=S0001, DB Errorcode=4145]
如何连接具有相同itemid
和 NULL version
的行?
编辑:也许这并不重要,但是在我的实际查询表中,表1和表2是选择结果,并且对于还包含itemid和版本的示例,我跳过了第三个选择。所以它是选择的联接。
在上一个示例中,您错误地使用了 ISNULL - 请尝试 -
SELECT t1.itemid,
t1.version,
t1.anything,
t2.something
FROM table1 AS t1
LEFT JOIN table2 AS t2
ON t1.itemid=t2itemid AND ISNULL(t1.version, '-') = ISNULL(t2.version, '-')
终于我找到了问题所在。似乎NULL 字段并不总是NULL
,有时NULL
字段包含的东西不是NULL
、''
或' '
我不知道这个字段到底包含什么,是一个不可见的字符。但幸运的是,版本字段总是以 V
开头,所以我在版本字段中放置了这个状态:
IIF (t1.version like 'V%', t1.version, NULL)
这样,我确保此字段包含NULL
值,然后一切似乎都正常工作。
如果不是"V%",这些值应该始终为 NULL,所以可能是由谁在数据库中引入行引起的......