I have 4 tables. From table1
, I would like to select postID
, status
, and data
. From table2
, I would like to select postID
, status
, and update
. Both table1 and table2 share 2 columns, which are the postID
and the userID
.
Table3 has a column postID
which is common to table2 and table2.
I would like to query data from table1 and table2 based on the userID
from the user table, then used the postID
to query data from table3.
$sql = "((SELECT `postID`, `status`, `data`
FROM `table1`
LEFT JOIN `users`
ON users.user_id=table1.userID
WHERE table1.userID=:userID
AND table1.active=:active)
UNION
(SELECT `postID`, `status`, `update`
FROM `table2`
LEFT JOIN `users`
ON users.user_id=table2.userID
WHERE table2.userID=:userID
AND table2.active=:active
ORDER BY table1.postID DESC))
AS tab12
LEFT JOIN `table3`
ON table3.postID=:tab12.postID
WHERE table3.active=:active";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(":userID", $userID, PDO::PARAM_INT);
$stmt->bindValue(":active", $active, PDO::PARAM_INT);
$stmt->execute();
How to go to table3 and select only some columns: status, update, timeDate, then associate the results to the previous query?
Something like:
$sql = "SELECT `status`, `update`, `timeDate`
FROM `table3`
WHERE postID=:tab12.postID
AND active=:active";
$stmt = $this->pdo->prepare($sql);
$stmt->bindValue(":postID", $postID, PDO::PARAM_INT);
$stmt->bindValue(":active", $active, PDO::PARAM_INT);
$stmt->execute();
Select result.PostID, result.Status, result.data, T2.Status,
result.update, user.status, user.update, user.timeDate
from (Select T1.PostID, T1.Status, T1.data, T2.Status, T2.update
from table1 as t1
union table2 as T2
where T1.UserID = T2.UserID) result
union user
where result.PostID = User.PostID
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.