有没有办法可以根据另一个表中字段的值有条件地改变我内部加入的表?这是我到目前为止所得到的(但错误):
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
因此,有一个表(作业)具有idType(经销商,集团或代理商)和clientID(称为经销商ID)。我需要做什么加入某个表(基于idType)来确定哪个销售经理“拥有”客户帐户。如果idType ='经销商',我需要加入smdealershipjoins,如果它是'Group'我需要加入smgroupjoins,如果'agency'我需要加入smagencyjoins,这样我就可以将该表加入userinfo以获得销售经理的名字。
我也尝试使用case语句来进行内部连接,但这也给出了错误。
答案 0 :(得分:7)
左/外连接到三个选项中的每一个,并且选择中的条件将处理其余选项。
也许是这样的:
...
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