加入带有 NULL 的 ID
Joining an ID with a NULL
我正在尝试将一个 table 数据加入另一个 table,但我要加入的其中一个 ID 是 NULL。但是,我有一个特定的 ID,我希望它 link 带有 NULL。
这个例子可能过于简化了这个问题,但我希望这会为我指明正确的方向。所以假设我们有下面的两个 table。
表 1:
Name ID
A 1
B 2
C NULL
表 2:
ID Value
1 4
2 5
3 6
我需要在查询中做什么才能得到这样的输出?
输出:
Name Value
A 4
B 5
C 6
在此先感谢您的帮助。
您可以在 on
子句中明确检查它:
SELECT name, value
FROM table1
JOIN table2 ON (table1.id = table2.id) OR
(table1.id IS NULL AND table2.id = 3)
使用 COALESCE(ID,3) 而不是 table1.id
加入
您可以在多个条件下加入,并在次要条件下加入您的特定场景:
select name, value
from table1 t1
inner join table2 t2 on t1.id = t2.id
or (t1.id is null and t2.id = 3)
SELECT name, value
FROM table1
JOIN table2 ON (table1.id = table2.id or table1.id IS NULL)
SELECT t1.Name AS Name , coalesce(t2.ID,standardvaluefornulls) AS ID
FROM table1 t1
LEFT JOIN table2 t2 ON t1.Value = t2.Value
编辑:这不适用于普通连接,因为它会跳过没有 t2.value 值的行,因此请记住您的左 table (t1)是始终具有 'Value' 值的那个,您可以使用左联接,因此即使 table2 中没有结果的那些也将获得标准空值作为结果
SQLFIDDLE 证明它有效:http://sqlfiddle.com/#!9/b2e15/12
如果知道具体ID:使用ISNULL
SELECT name, value
FROM table1
JOIN table2 ON ISNULL(table1.id,3) = table2.id
我正在尝试将一个 table 数据加入另一个 table,但我要加入的其中一个 ID 是 NULL。但是,我有一个特定的 ID,我希望它 link 带有 NULL。
这个例子可能过于简化了这个问题,但我希望这会为我指明正确的方向。所以假设我们有下面的两个 table。
表 1:
Name ID
A 1
B 2
C NULL
表 2:
ID Value
1 4
2 5
3 6
我需要在查询中做什么才能得到这样的输出?
输出:
Name Value
A 4
B 5
C 6
在此先感谢您的帮助。
您可以在 on
子句中明确检查它:
SELECT name, value
FROM table1
JOIN table2 ON (table1.id = table2.id) OR
(table1.id IS NULL AND table2.id = 3)
使用 COALESCE(ID,3) 而不是 table1.id
加入您可以在多个条件下加入,并在次要条件下加入您的特定场景:
select name, value
from table1 t1
inner join table2 t2 on t1.id = t2.id
or (t1.id is null and t2.id = 3)
SELECT name, value
FROM table1
JOIN table2 ON (table1.id = table2.id or table1.id IS NULL)
SELECT t1.Name AS Name , coalesce(t2.ID,standardvaluefornulls) AS ID
FROM table1 t1
LEFT JOIN table2 t2 ON t1.Value = t2.Value
编辑:这不适用于普通连接,因为它会跳过没有 t2.value 值的行,因此请记住您的左 table (t1)是始终具有 'Value' 值的那个,您可以使用左联接,因此即使 table2 中没有结果的那些也将获得标准空值作为结果
SQLFIDDLE 证明它有效:http://sqlfiddle.com/#!9/b2e15/12
如果知道具体ID:使用ISNULL
SELECT name, value
FROM table1
JOIN table2 ON ISNULL(table1.id,3) = table2.id