简体   繁体   English

在一个查询中查询4个MySQL表

[英]Querying 4 MySQL tables in one query

I'm building a forums site and I would like to display all the threads to users in the following format: 我正在建立一个论坛站点,我想以以下格式向用户显示所有主题:

_________________________________________________________________________
Thread Title
Last Post: Username at Date, Started By: Username at Date
_________________________________________________________________________

This is what I've come up with: 这是我想出的:

         SELECT TD.id       thread_id,
                TD.sub_cat  thread_cat,
                TD.title    thread_title,
                TD.date     thread_date,
                TD.status   thread_status,
                TD.stick    thread_stick,

                US.username user,

                GR.color group_color

        FROM fr_thread AS TD
        INNER JOIN user AS US ON TD.user_id = US.id
        INNER JOIN user_group AS GR ON US.user_group = GR.id
        ORDER BY TD.stick

While I'm displaying all the threads, I would also like the username's be to coloured according to what user group they are in. Therefore, I also have to query for that. 在显示所有线程时,我还希望根据其所在的用户组对用户名进行着色。因此,我还必须进行查询。

Although, I've come up with most of query, I'm stuck as how to query for Username, group color, date of the last poster. 尽管我提出了大部分查询条件, 但仍困扰于如何查询用户名,组颜色,最后张贴者的日期。

Here is roughly what my DB design looks like: 我的数据库设计大致如下:

user:
id
user_group

user_group:
id
color

fr_thread:
id
sub_cat
user_id
date

fr_reply:
id
thread_id
user_id
date

Try 尝试

SELECT  

    TD.id as thread_id , 
    TD.sub_cat as thread_sub_cat , 
    TD.user_id as thread_started_user_id , 
    TD.date as thread_started_on , 

    US1.name as thread_author , 
    US2.id as last_reply_user_id , 
    US2.name as last_reply_user_name , 

    USG1.color as thread_author_color ,  
    USG2.color as lat_reply_user_color , 

    RE.date as last_reply_date 

FROM  

    fr_thread TD join user US1 on TD.user_id = US1.id

    join user_group USG1 on USG1.id = US1.user_group 

    join fr_reply RE on RE.thread_id = TD.id

    join user US2 on US2.id = RE.user_id 

    join user_group USG2 on USG2.id = US2.user_group

Created 2 aliases for user table as US1 and US2 and there are 2 involved ( creator and last replier) similary for user_group user表创建了2个别名US1US2 ,并且user_group涉及2个(创建者和最后一个回复者)相似user_group

http://sqlfiddle.com/#!9/951c0b/1 http://sqlfiddle.com/#!9/951c0b/1

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM