0

我能够join2 个表中获取信息,以便输出哪些用户说哪些状态。它设法获取用户状态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'");
4

3 回答 3

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

于 2013-08-09T17:43:52.003 回答
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 的任一侧使用。

于 2013-08-09T17:42:58.193 回答
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'
于 2013-08-09T17:46:01.497 回答