[英]How to select multiple rows from different tables using MYSQL
我有 4 張桌子。 從table1
中,我想 select postID
、 status
和data
。 從table2
2 中,我想 select 的postID
、 status
和update
。 table1 和 table2 共享 2 列,即postID
和userID
。
表 3 有一個表 2 和表 2 共有的postID
列。
我想根據用戶表中的userID
從table1和table2中查詢數據,然后使用postID
從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();
如何將 go 到 table3 和 select 僅一些列:status、update、timeDate,然后將結果關聯到前面的查詢?
就像是:
$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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.