【问题标题】:How to select multiple rows from different tables using MYSQL如何使用MYSQL从不同的表中选择多行
【发布时间】:2022-08-14 06:20:05
【问题描述】:

我有 4 张桌子。从table1,我想选择postIDstatusdata。从table2,我想选择postIDstatusupdate。 table1 和 table2 共享 2 列,分别是 postIDuserID
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();

标签: mysql sql join select union


【解决方案1】:
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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-11-01
    • 2022-01-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-26
    • 1970-01-01
    相关资源
    最近更新 更多