问题描述
我希望基于两个条件执行左连接:
SELECT
...
FROM
soMetable AS a
LEFT JOIN someothertable AS b ON a.some_id = b.some_id
AND b.other_id IN (1,2,3,4)
我收到错误:
支持的语法:JOIN ON Expr([table.]column,...) = Expr([table.]column,...) [AND Expr([table.]column,...) = Expr( [table.]column,...) ...]```
似乎join的条件必须是=
,不能是in
有什么想法吗?
解决方法
考虑将 IN 运算符移动到子查询中:
SELECT
a.number,b.number
FROM numbers(8) AS a
LEFT JOIN
(
SELECT *
FROM numbers(234)
WHERE number IN (1,2,3,4)
) AS b USING (number)
/*
┌─number─┬─b.number─┐
│ 0 │ 0 │
│ 1 │ 1 │
│ 2 │ 2 │
│ 3 │ 3 │
│ 4 │ 4 │
│ 5 │ 0 │
│ 6 │ 0 │
│ 7 │ 0 │
└────────┴──────────┘
*/
或
SELECT
a.number,4)
) AS b USING (number)
SETTINGS join_use_nulls = 1 /* 1 is 'JOIN behaves the same way as in standard SQL. The type of the corresponding field is converted to Nullable,and empty cells are filled with NULL.' */
/*
┌─number─┬─b.number─┐
│ 0 │ ᴺᵁᴸᴸ │
│ 1 │ 1 │
│ 2 │ 2 │
│ 3 │ 3 │
│ 4 │ 4 │
│ 5 │ ᴺᵁᴸᴸ │
│ 6 │ ᴺᵁᴸᴸ │
│ 7 │ ᴺᵁᴸᴸ │
└────────┴──────────┘
*/