有没有一种方法可以根据另一个表中字段的值有条件地更改我内部加入的表?这是我到目前为止得到的(但它错误):
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(dealership、group 或 Agency)和 clientID(称为dealershipID)。我需要做的是加入某个表(基于 idType)以确定哪个销售经理“拥有”客户帐户。如果 idType = 'dealership' 我需要加入 smdealershipjoins,如果是 'Group' 我需要加入 smgroupjoins,如果它是 'agency' 我需要加入 smagencyjoins 以便我可以将该表加入 userinfo 以获得销售额经理的名字。
我也尝试使用 case 语句进行内部连接,但这也产生了错误。