从具有紧密WHERE子句的四个表中获取数据

时间:2014-08-18 18:30:27

标签: php mysql sql

我需要帮助从不同的表中获取数据并插入到其他不同的表中以下是查询

"SELECT commentID, date, comment, subject, parentID, aBUserID FROM comments WHERE status = 'APPROVED'"

"SELECT topicID, subForumID, aBUserID, lastPostID, views, replies, startDate FROM topic WHERE status = 'APPROVED' AND topicID = $parentid";
 // $parentID need to be matched from above query parentID,

"SELECT userName FROM users WHERE aBUserID = $cmtaBUserID";
// $cmtaBUserID = aBUserID from first query

"SELECT userName FROM users WHERE aBUserID = $topicaBUserID";
//$topicaBUserID = aBUserID from second query

最后2个查询来自同一个表但使用不同的where子句 我使用了不同的内部加入左连接来自这里发布的解决方案,但是这些都没有为我工作,因为自从过去2周以来请帮助

来自以上所有查询的PS数据将被插入到单个表中,我需要将它们组合在一起,这样我就可以将它们全部放在一个地方

4 个答案:

答案 0 :(得分:0)

如果要在同一查询中执行操作,请使用“OR”

“SELECT userName FROM users WHERE aBUserID = $ cmtaBUserID OR aBUserID = $ topicaBUserID”;

答案 1 :(得分:0)

请试试这个

userName中选择users aBUserID IN(SELECT aBUserID FROM comments WHERE status =' APPROVED')

答案 2 :(得分:0)

无法测试,但也许这就是你要找的东西。

SELECT c.commentID, c.date, c.comment, c.subject, c.parentID, c.aBUserID, 
       t.topicID, t.subForumID, t.aBUserID, t.lastPostID, t.views, t.replies, t.startDate,
       u.userName
FROM 
       comments c 
       left outer join topic t on t.topicID = c.parentID
       left outer join users u on u.aBUserID = c.aBUserID and u.aBUserID = t.aBUserID
WHERE
       c.status = 'APPROVED' and t.status = 'APPROVED';

答案 3 :(得分:0)

试试这个:

SELECT
    comment.[commentID],
    comment.[date],
    comment.[comment],
    comment.[subject],
    comment.[parentID],
    comment.[aBUserID], 
    commentuser.[userName],
    topic.[topicID],
    topic.[subForumID],
    topic.[aBUserID],
    topic.[lastPostID],
    topic.[views],
    topic.[replies],
    topic.[startDate],
    topic.[userName]
FROM comments comment
LEFT OUTER JOIN users commentuser
    ON commentuser.aBUserID = comment.[aBUserID]
LEFT OUTER JOIN
(
    SELECT
        t.[topicID],
        t.[subForumID],
        t.[aBUserID],
        t.[lastPostID],
        t.[views],
        t.[replies],
        t.[startDate],
        u2.[userName] --user from users table joined to topics table
    FROM topic t
    LEFT OUTER JOIN users u
        ON u.aBUserID = t.[aBUserID]
    WHERE t.[status] = 'APPROVED'
) topic
    ON topic.topicID = comment.parentID
WHERE comment.[status] = 'APPROVED'