我有4张桌子:
ADS
:ID,文字,数字
TABLE2
:id,user_id,数字
TABLE3
:id,user_id,数字
TABLE4
:id,user_id,数字
user_id不是唯一的。可以存在与否。
输出我希望:
如果ADS
表的数量等于TABLE1
或TABLE2
或TABLE3
的数字,则仅显示文字的。
我试过了:
SELECT ADS.text FROM ADS
LEFT JOIN TABLE2 ON TABLE2.user_id = ?
LEFT JOIN TABLE3 ON TABLE3.user_id = ?
LEFT JOIN TABLE4 ON TABLE4.user_id = ?
WHERE ADS.number = TABLE2.number OR
ADS.number = TABLE3.number OR
ADS.number = TABLE4.number
GROUP BY ADS.id
和
SELECT * FROM
(
SELECT
ADS.text FROM ADS
LEFT JOIN TABLE2 ON TABLE2.user_id = ?
LEFT JOIN TABLE3 ON TABLE3.user_id = ?
LEFT JOIN TABLE4 ON TABLE4.user_id = ?
WHERE ADS.number = TABLE2.number OR
ADS.number = TABLE3.number OR
ADS.number = TABLE4.number
UNION ALL
SELECT
ADS.text FROM ADS
LEFT JOIN TABLE2 ON TABLE2.user_id = ?
LEFT JOIN TABLE3 ON TABLE3.user_id = ?
LEFT JOIN TABLE4 ON TABLE4.user_id = ?
WHERE ADS.number = TABLE2.number OR
ADS.number = TABLE3.number OR
ADS.number = TABLE4.number
) request
ORDER BY ADS.id
$reponse->execute(array($_SESSION['id'],$_SESSION['id'],$_SESSION['id']));
我的输出总是太多或不够......
答案 0 :(得分:1)
这样做你想要的吗?
SELECT ADS.text
FROM ADS a
WHERE EXISTS (SELECT 1 FROM TABLE2 t WHERE t.user_id = ? AND t.number = a.number) OR
EXISTS (SELECT 1 FROM TABLE3 t WHERE t.user_id = ? AND t.number = a.number) OR
EXISTS (SELECT 1 FROM TABLE4 t WHERE t.user_id = ? AND t.number = a.number);