我想要这种输出
ID Status
100 Viewed
103 Not Viewed
105 Viewed
这是我的sql:
select id, status from status_table where ID in (100, 101,102,103,104,105);
它将显示上面的结果,因为在状态表中其他id没有任何条目。ID is foreign key of another table named as table_file table. It contains in another database. So I cannot join the table due to some performance issue.
所以我以逗号分隔的值传递文件ID。但我想要这样的结果,我怎么能在不使用任何循环的情况下创建它呢。
ID Status
100 Viewed
101 Not
102 Not
103 Viewed
104 Not
105 Viewed
有可能吗?请帮帮我。
您有一个表中确实存在这些ID吗?这样你就可以加入了?
SELECT
source.ID,
status.value
FROM
source
LEFT JOIN
status
ON status.id = source.id
WHERE
source.ID in (100, 101,102,103,104,105);
如果没有,则需要创建一个临时表或内联表(其中包含这些值)。然后您可以将该表连接到您的数据中。
编辑
内联表的示例。有几种方法可以做到这一点,这只是其中之一。
SELECT
source.ID,
status.value
FROM
(
SELECT 100 AS id UNION ALL
SELECT 101 AS id UNION ALL
SELECT 102 AS id UNION ALL
SELECT 103 AS id UNION ALL
SELECT 104 AS id UNION ALL
SELECT 105 AS id
)
AS source
LEFT JOIN
status
ON status.id = source.id
当ID
丢失时,假设"不是",可以这样做:
SELECT
so.ID,
CASE WHEN st.value IS NULL THEN 'Not' ELSE st.value END
FROM
databasename1..source so
LEFT JOIN
databasename2..status st
ON st.id = so.id
WHERE
so.ID in (100, 101,102,103,104,105)
将databasename1
和databasename2
替换为实database names
。