组合2个JOINS时遇到问题。以下两个陈述都有效。我还在2个DB中包含了相关字段。我的问题是: 1)如何将2个语句合并为1个语句? 2)如何引用我的php中的行来区分结果是来自mmpreID JOIN还是mmparID JOIN?
由于
DB: matchmaker
mmpreID
mmparID
DB: users
uID
ufname
ulname
SELECT matchmaker.mmpreID, matchmaker.mmparID, users.uID, users.ufname, users.ulname
FROM matchmaker
LEFT JOIN users ON matchmaker.mmparID = users.uID
SELECT matchmaker.mmpreID, matchmaker.mmparID, users.uID, users.ufname, users.ulname
FROM matchmaker
LEFT JOIN users ON matchmaker.mmpreID = users.uID
答案 0 :(得分:5)
SELECT m.mmpreID, m.mmparID, u.uID, u.ufname, u.ulname,
case
when m.mmparID = u.uID then 'mmparID'
when m.mmpreID = u.uID then 'mmpreID'
else null
end as Source
FROM matchmaker m
LEFT JOIN users u ON m.mmparID = u.uID or m.mmpreID = u.uID
<强>更新强>
SELECT m.mmpreID, m.mmparID,
upar.uID as upar_UID,
upar.ufname as upar_UFNAME,
upar.ulname as upar_ULNAME,
upre.uID as upre_UID,
upre.ufname as upre_UFNAME,
upre.ulname as upre_ULNAME
FROM matchmaker m
LEFT JOIN users upar ON m.mmparID = upar.uID
LEFT JOIN users upre ON m.mmpreID = upre.uID
答案 1 :(得分:-1)
添加UNION和另一列以查看它来自哪里
SELECT matchmaker.mmpreID, matchmaker.mmparID, users.uID,
users.ufname, users.ulname, "mmpar only" as source
FROM matchmaker
LEFT JOIN users ON matchmaker.mmparID = users.uID AND matchmaker.mmparID != matchmaker.mmpreID
UNION
SELECT matchmaker.mmpreID, matchmaker.mmparID, users.uID,
users.ufname, users.ulname, "mmpre only" as source
FROM matchmaker
LEFT JOIN users ON matchmaker.mmpreID = users.uID
AND matchmaker.mmparID != matchmaker.mmpreID
UNION
SELECT matchmaker.mmpreID, matchmaker.mmparID, users.uID,
users.ufname, users.ulname, "both" as source
FROM matchmaker
LEFT JOIN users ON matchmaker.mmpreID = users.uID AND matchmaker.mmparID = matchmaker.mmpreID
修改上述答案,包括3种可能的结果 1. uID仅匹配mmparID 2. uID仅匹配mmpreID 3. uID匹配mmparID和mmpreID
是的,UNIONS效率不高,但有时需要它们