I am trying to do a UNION
on 4 tables to get the ID's from each table, WHERE the USER_ID = $_SESSION['uid']
I will explain each query to give you an idea of where I came from, and where I am going.
The first query works fine, the problem: only ID's
of each record. I need to left JOIN to get each records corresponding data.
SELECT DISTINCT(bid_id) FROM bids_questions
UNION SELECT DISTINCT(bid_id) FROM bids_qualify_requests WHERE type = 'Prequalified'
UNION SELECT DISTINCT(bid_id) FROM bids_documents_download
UNION SELECT DISTINCT(bid_id) FROM bids_documents_upload
WHERE uid=? GROUP BY bid_id
$stmt->bind_param('i', $_SESSION['uid']);
In the second attempt I add a left join. This query works fine, however it lacks the WHERE
clause that specified the user ID.
SELECT
bid_id.bid_id,//BID ID's
b.title,
u.name
FROM (
SELECT DISTINCT(bid_id) FROM bids_questions
UNION SELECT DISTINCT(bid_id) FROM bids_qualify_requests WHERE type = 'Prequalified'
UNION SELECT DISTINCT(bid_id) FROM bids_documents_download
UNION SELECT DISTINCT(bid_id) FROM bids_documents_upload
) AS bid_id
LEFT JOIN bids b ON b.bid_id = bid_id.bid_id
LEFT JOIN users u on b.uid = u.uid
GROUP BY bid_id
If I try to add the WHERE
clause in there, I get an error saying the column does not exist.
SELECT
bid_id.bid_id,//BID ID's
b.title,
u.name
FROM (
SELECT DISTINCT(bid_id) FROM bids_questions
UNION SELECT DISTINCT(bid_id) FROM bids_qualify_requests WHERE type = 'Prequalified'
UNION SELECT DISTINCT(bid_id) FROM bids_documents_download
UNION SELECT DISTINCT(bid_id) FROM bids_documents_upload
) AS bid_id
LEFT JOIN bids b ON b.bid_id = bid_id.bid_id
LEFT JOIN users u on b.uid = u.uid
WHERE bid_id.uid=?
GROUP BY bid_id
$stmt->bind_param('i', $_SESSION['uid']);
Is there a way I can add the WHERE
clause that applies to every inner query? I am sure I could add a separate WHERE
in each query and bind a param for each. Or maybe I select UID and bid_id from all tables then select only the UID out of that table? I want the optimal performance option as this DB will be quite large. Any ideas?
question from:
https://stackoverflow.com/questions/65878736/how-to-do-where-clause-in-union-and-left-join 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…