Php 使用WHERE子句从四个表中获取数据

Php 使用WHERE子句从四个表中获取数据,php,mysql,sql,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'

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

"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
最后两个查询来自同一个表,但使用不同的where子句 我使用了不同的内部连接左连接从解决方案张贴在这里,但没有这些工作为我卡住,因为过去2周请帮助


所有上述查询中的PS数据将被插入到一个表中。我需要将这些数据组合在一起,以便我可以将它们全部放在一个位置上

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

从以下用户中选择用户名:aBUserID=$cmtaBUserID或aBUserID=$topicaBUserID

请试试这个


从用户中选择用户名,在用户中输入aBUserID从状态为“已批准”的评论中选择aBUserID

无法测试它,但这可能是您正在寻找的

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';
试试这个:

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'

你需要什么帮助?连接到数据库?获取正确的数据?遍历结果集?您的数据库是什么样子的?您的PHP代码在哪里?谢谢,我需要使用join as$组合这些查询。以上查询中的条件不会返回任何数据和查询失败,或者,您也可以使用IN,我发现这更容易阅读。两个查询返回的数据都不会被处理为表的不同字段以插入,因此无法使用ORYes这就是我要找的内容。非常感谢关于左侧外部连接的更多帮助用户u on u.aBUserID=c.aBUserID和u.aBUserID=t.aBUserID我可以将用户名与主题分开吗注释“能够分离”中的表和用户名?什么意思?