gpt4 book ai didi

sql-server - sql : select rows based on another table if is populated or empty

转载 作者:行者123 更新时间:2023-12-02 03:39:38 25 4
gpt4 key购买 nike

我有两张 table 。第一个称为 TempIds,它只包含一个名为 Id 的列,其类型为 int

临时 ID:

Id
45
34
77

第二个称为“国家/地区”,有两列:“ID”和“名称”国家:

Id      Name
22 Austria
45 Germany
88 China
12 Japan

我想要的是从国家表中选择与 TempIds 表中的 Id 匹配的所有行。但问题是,如果 TempIds 为空,则查询应返回国家/地区的所有行。

到目前为止,这是我尝试过的:

select *
from Countries c
left join TempIds t on c.Id = t.Id or t.Id is null


select *
from Countries c
left join TempIds t on c.Id = t.Id
where (c.Id = t.Id or t.Id is null)

上面的两个查询都没有返回正确的记录。我的问题是,如何编写一个返回正确结果的查询。也就是说,根据当前的 TempIds 表,我应该只获得德国。但如果 TempIds 为空,那么我应该从“国家”表中获取所有国家/地区。

先谢谢了

最佳答案

非常基本但可以尝试:->

SELECT c.* 
FROM
countries c LEFT OUTER JOIN tempids t
ON c.id = t.id
WHERE
t.id is not null
OR NOT EXISTS (SELECT 1 FROM tempids)

另一个选项:->

WITH CTE as 
(
SELECT
c.id, c.name, t.id as t_id
FROM
countries c LEFT OUTER JOIN tempids t
on c.id = t.id
)
SELECT *
FROM CTE
WHERE
t.id is not null
OR NOT EXIST (
SELECT 1
FROM cte
WHERE t_id is not null
)

或者非常简单的是先检查 tempid 的表计数,然后决定查询:->

IF exists(select 1 from tempid)
BEGIN
SELECT c.*
FROM
countries c INNER JOIN tempids t
ON c.id = t.id
END
ELSE
BEGIN
SELECT * from countries
END

请不要介意格式。

关于sql-server - sql : select rows based on another table if is populated or empty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49081415/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com