gpt4 book ai didi

mysql - MySQL 中的条件内连接语句

转载 作者:行者123 更新时间:2023-11-29 01:13:50 25 4
gpt4 key购买 nike

有没有一种方法可以根据另一个表中字段的值有条件地更改我内部加入的表?这是我到目前为止(但它出错)的结果:

SELECT 
j.jobID, j.jobNumber,
CASE
WHEN j.idType = 'dealership' THEN d.dealershipName
WHEN j.idType = 'Group' THEN g.groupName
WHEN j.idType = 'Agency' then a.agencyName
END as dealershipName,
CASE
WHEN p.manualTimestamp != '0000-00-00 00:00:00' THEN UNIX_TIMESTAMP(p.manualTimestamp)
WHEN p.manualTimestamp = '0000-00-00 00:00:00' THEN p.timestamp
END as checkTS,
CONCAT_WS(' ', ui.fName, ui.lName) as salesRep
FROM jobs j
LEFT JOIN dealerships d ON j.dealershipID = d.dealershipID
LEFT JOIN dealershipgroups g ON j.dealershipID = g.groupID
LEFT JOIN agencies a ON j.dealershipID = a.agencyID
INNER JOIN payments p ON j.jobID = p.jobID
IF j.idType = 'dealership' THEN
INNER JOIN smdealershipjoins smdj ON j.dealershipID = smdj.dealership
INNER JOIN userinfo ui ON smdj.sm = ui.userID
ELSEIF j.idType = 'Group' THEN
INNER JOIN smgroupjoins gj ON j.dealershipID = gj.groupID
INNER JOIN userinfo ui ON gj.sm = ui.userID
ELSEIF j.idType = 'Agency' THEN
INNER JOIN smagencyjoins aj ON j.dealershipID = aj.agencyID
INNER JOIN userinfo ui on aj.sm = ui.userID
END IF

因此,有一个表 (jobs),其中包含 idType(经销商、集团或代理)和一个 clientID(称为 dealershipID)。我需要做的是加入某个表(基于 idType)以确定哪个销售经理“拥有”客户帐户。如果 idType = 'dealership' 我需要加入 smdealershipjoins,如果它是 'Group' 我需要加入 smgroupjoins,如果它是 'agency' 我需要加入 smagencyjoins 这样我就可以将该表加入 userinfo 以获得销售经理的名字。

我也尝试过使用 case 语句来进行内部连接,但这也报错了。

最佳答案

左/外连接到三个选项中的每一个,您选择的条件将处理其余部分。

也许是这样的:

...
LEFT JOIN smdealershipjoins smdj
ON j.dealershipID = smdj.dealership
LEFT JOIN smgroupjoins gj
ON j.dealershipID = gj.groupID
LEFT JOIN smagencyjoins aj
ON j.dealershipID = aj.agencyID
LEFT JOIN userinfo ui
ON ui.userID = CASE
WHEN j.idType = 'dealership' THEN smdj.sm
WHEN j.idType = 'Group' THEN gj.sm
WHEN j.idType = 'Agency' then aj.sm
END

关于mysql - MySQL 中的条件内连接语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15640321/

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