【发布时间】:2022-08-14 06:20:05
【问题描述】:
我有 4 张桌子。从table1,我想选择postID、status和data。从table2,我想选择postID、status和update。 table1 和 table2 共享 2 列,分别是 postID 和 userID。
Table3 有一个列postID,它是 table2 和 table2 共有的。
我想根据用户表中的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();
如何去 table3 只选择一些列: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();
-
在寻求帮助时,minimal reproducible example 是一个很好的开始。
标签: mysql sql join select union