这是我的查询:
SELECT numit,id FROM pecas where numit in (40363, 40366, 40310, 40320, 40362, 40364, 40385, 40415);
结果是:
numit | id
40363 50
40362 65
我想在IN子句中获取所有'numit'值,如果找不到对应的ID,则将'id'列替换为NULL。
numit | id
40362 65
40363 50
40366 NULL
40310 NULL
40320 NULL
40364 NULL
40385 NULL
40415 NULL
答案 0 :(得分:1)
这是我到目前为止最简单的方法。它需要使用IN
子句中的所有值创建一个伪表,以便将它们包含在结果中。当然,如果可以将IN
子句值作为同一张或另一张表中的行的列表来提取,则可以简化它(但如果是这种情况,则需要编辑问题)。
SELECT p.numit, p.id FROM pecas p WHERE p.numit IN (40363, 40366, 40310, 40320, 40362, 40364, 40385, 40415)
UNION
SELECT * FROM
( SELECT 40363 AS numit, NULL AS id
UNION
SELECT 40366 AS numit, NULL AS id
UNION
SELECT 40310 AS numit, NULL AS id
UNION
SELECT 40320 AS numit, NULL AS id
UNION
SELECT 40362 AS numit, NULL AS id
UNION
SELECT 40364 AS numit, NULL AS id
UNION
SELECT 40385 AS numit, NULL AS id
UNION
SELECT 40415 AS numit, NULL AS id
) t WHERE t.numit NOT IN (SELECT p2.numit FROM pecas p2 WHERE p2.numit IN (40363, 40366, 40310, 40320, 40362, 40364, 40385, 40415))
答案 1 :(得分:0)
如果where子句中的数字数据来自其他表,则可以使用左连接。
SELECT
product_name,
order_id
FROM
production.products p
LEFT JOIN sales.order_items o ON o.product_id = p.product_id
where o.product_id in(40363, 40366, 40310, 40320, 40362, 40364, 40385, 4041,4363, 466, 310, 1320, 4032, 40364, 440385, 41041)
ORDER BY
order_id;
答案 2 :(得分:0)
我想您可以先使用UNION子句组合它们,然后按如下所示获取最大ID-
SELECT numit, MAX(id)
FROM (SELECT numit,id
FROM pecas
WHERE numit in (SELECT itext FROM pecas)
UNION
SELECT itext, NULL
FROM pecas) T
GROUP BY numit;
答案 3 :(得分:0)
请尝试以下操作:
select numit,
case id in (40363, 40366, 40310, 40320, 40362, 40364, 40385, 40415) then id
else Null
end id
from pecas