Difficulty with join 3 tables in a query in php

前端 未结 2 1487
灰色年华
灰色年华 2021-01-23 22:50

My database has 3 tables i wish to access in the select query but I cannot seem to get it to work. Selecting from 2 tables works fine so I know everything else is working apart

相关标签:
2条回答
  • 2021-01-23 23:20

    You miss the , after users.username..

    SELECT forum_replies.reply_id, forum_replies.topic_id, forum_replies.user_id,
    forum_replies.reply_text, forum_replies.reply_date, users.user_id, users.username,
     forum_topics.topic_id,forum_topics.topic_title, forum_topics.topic_date
    
    0 讨论(0)
  • 2021-01-23 23:35

    Use this query:

    SELECT a.reply_text, a.reply_date, b.topic_title, c.username
    FROM forum_replies a
    LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
    LEFT JOIN users c ON a.user_id=c.user_id
    // apply WHERE, ORDER, GROUP if needed
    

    Apart from syntax errors, you should use LEFT JOIN and table alias in your case.


    To show also the topic creator's username, you can adjust the query to the following:

    SELECT a.reply_text, a.reply_date, b.topic_title, c.username AS reply_user, (SELECT username FROM users WHERE user_id=b.user_id) AS topic_creator
    FROM forum_replies a
    LEFT JOIN forum_topics b ON a.topic_id=b.topic_id
    LEFT JOIN users c ON a.user_id=c.user_id
    // apply WHERE, ORDER, GROUP if needed
    
    0 讨论(0)
提交回复
热议问题