[英]How to select multiple rows from different tables using MYSQL
I have 4 tables.我有 4 张桌子。 From table1
, I would like to select postID
, status
, and data
.从table1
中,我想 select postID
、 status
和data
。 From table2
, I would like to select postID
, status
, and update
.从table2
2 中,我想 select 的postID
、 status
和update
。 Both table1 and table2 share 2 columns, which are the postID
and the userID
. table1 和 table2 共享 2 列,即postID
和userID
。
Table3 has a column postID
which is common to table2 and table2.表 3 有一个表 2 和表 2 共有的postID
列。
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.我想根据用户表中的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();
How to go to table3 and select only some columns: status, update, timeDate, then associate the results to the previous query?如何将 go 到 table3 和 select 仅一些列:status、update、timeDate,然后将结果关联到前面的查询?
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.