加入2个以上的表以循环结果

时间:2013-08-09 17:40:46

标签: sql join left-join

我能够从 2个表join信息,以便输出哪些用户说明了哪个状态。 它设法从tbl_status获取用户状态,并从tbl_users获取用户的用户名。

但是现在我还要添加用户照片以及状态更新,并在同一查询中输出该信息。毫不奇怪,用户照片包含在tbl_photos

如何将此附加查询添加到现有输出中以使用上一个查询输出结果?

$result = mysql_query("SELECT tbl_status.id as statID, tbl_status.from_user as statFROM, tbl_status.status as statSTATUS, tbl_status.deleted as statDEL, tbl_status.date as statDATE, tbl_users.id as usrID, tbl_users.name as usrNAME FROM tbl_status INNER JOIN tbl_users ON tbl_status.from_user = tbl_users.id WHERE tbl_status.deleted = '0'");

3 个答案:

答案 0 :(得分:1)

我添加了一个左连接,以防用户没有照片或可选。

SELECT  tbl_status.id AS statID ,
            tbl_status.from_user AS statFROM ,
            tbl_status.status AS statSTATUS ,
            tbl_status.deleted AS statDEL ,
            tbl_status.date AS statDATE ,
            tbl_users.id AS usrID ,
            tbl_users.name AS usrNAME,
            p.photo
    FROM    tbl_status
            INNER JOIN tbl_users ON tbl_status.from_user = tbl_users.id
            Left JOIN tbl_photos p ON tbl_users.id = tbl_photos.userId
    WHERE   tbl_status.deleted = '0'

但是,如果每个用户都有照片,请使用...

SELECT  tbl_status.id AS statID ,
        tbl_status.from_user AS statFROM ,
        tbl_status.status AS statSTATUS ,
        tbl_status.deleted AS statDEL ,
        tbl_status.date AS statDATE ,
        tbl_users.id AS usrID ,
        tbl_users.name AS usrNAME,
        p.photo
FROM    tbl_status
        INNER JOIN tbl_users ON tbl_status.from_user = tbl_users.id
        INNER JOIN tbl_photos p ON tbl_users.id = tbl_photos.userId
WHERE   tbl_status.deleted = '0'

你也没有指定FK是什么,所以我只提了一个tbl_users.id = tbl_photos.userId,你需要将这一行和你从tbl_photo表中提取的字段替换为我使用p.photo

答案 1 :(得分:0)

你会扩展

FROM tbl_status INNER JOIN tbl_users ON tbl_status.from_user = tbl_users.id

FROM tbl_status INNER JOIN tbl_users ON tbl_status.from_user = tbl_users.id
     INNER JOIN tbl_photo ON tbl_photo.user_id = tbl_users.id

连接的结果被视为一个表,其中两个表的所有列在SQL中彼此相邻,因此可以在另一个JOIN的任一侧使用。

答案 2 :(得分:0)

您需要做的只是JOIN表上的另一个tbl_photos

我必须对tbl_photos做一些假设。

SELECT <all your existing columns>, ISNULL(tbl_photos.profile_filename, 'Default Filename') as ProfilePic
FROM tbl_status
INNER JOIN tbl_users ON tbl_status.from_user = tbl_users.id
LEFT JOIN tbl_photos ON tbl_photos.user_id = tbl_users.id
WHERE tbl_status.deleted = '0'