gpt4 book ai didi

mysql - 使用 Mysql 进行复杂查询

转载 作者:太空宇宙 更新时间:2023-11-03 10:41:59 25 4
gpt4 key购买 nike

我有以下架构

table Std
--------------
id int(11)
conf_id varchar(100)
name varchar(255)
for_all_sponsors tinyint(1)

table sts
------------
task_def_id int(11) NO
sponsor_id int(11) NO
status varchar(255) NO

加入条件为sts.task_def_id=std.id。

现在,sts 中可能有也可能没有对应于 std 的条目。

我想写一个这样的查询“获取 std 中的所有条目,其中 for_all_sponsors=1 且 conf_id 设置为‘c’。如果 sts 中有对应的条目,sponsor_id 设置为‘5’,则获取状态。如果没有条目,sponsor_id 设置为‘ 5',默认为'默认状态'。"

第一部分可以通过左外连接实现,其中 sponsor_id=5。

默认状态部分很棘手。有没有办法使用单个查询来执行此操作?

什么是最有效的查询方式,

编辑

我目前的情况是

select * from std left outer join sts on std.id=sts.task_def_id where std.for_all_sponsors=1 and std.conf_id='c' and sts.sponsor_id=5;

最佳答案

你可以试试这个:

SELECT Std.*, 
CASE WHEN sts.status IS NULL THEN 'default status' ELSE [status] END as Status
FROM Std
LEFT JOIN sts ON Std.id = sts.task_def_id AND sponsor_id = 'x'
WHERE for_all_sponsors = 1
AND conf_id = 'c'

关于mysql - 使用 Mysql 进行复杂查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36875167/

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