sql中的多个where子句

时间:2015-03-16 19:58:35

标签: mysql inner-join where-clause

我不知道这是否可行,但我会尝试一下。

我有3张桌子:

第一个表:( sender_id和receiver_id是引用loginportal表的外键)

messages
sender_id | receiver_id | message
    3     |      1      |   ...

第二个表:( req_id是外键引用请求表)

loginportal
loginPortal_id | username | req_id
     1         |   admin  |    1
     3         |    user  |    2

第三张表:

request
req_id | firstname | surname
   1   |    john   |   doe
   2   |    jane   |   me

问题:

每当我使用此查询时:

"SELECT id, message_sender_id, 
        message_title, message_body, sent_date, message_status,
        username, firstname, surname
        FROM messages m
        INNER JOIN loginportal l
        INNER JOIN request r
        ON m.message_receiver_id= l.loginPortal_id
        AND l.req_id=r.req_id
        WHERE m.message_receiver_id=(
        SELECT loginPortal_id FROM loginportal 
        WHERE username='".$_SESSION['user']."')";

我得到的是接收者用户名和接收者名字和姓氏。 我想要的是我将拥有接收者用户名,但SENDER的名字和姓氏。这有可能吗?

1 个答案:

答案 0 :(得分:0)

我认为您需要添加一个message_id字段,然后将两个子查询组合在一起,在其新的message_id上​​查找发件人和收件人信息。这些方面的东西......还没有测试过它

SELECT query1.username, query2.firstname, query2.surname

FROM (SELECT username, message_id FROM loginportal, messages WHERE loginPortal_id = receiver_id) AS query1,
(SELECT firstname, surname, message_id FROM request, loginportal, messages WHERE request.req_id = loginportal_req.id AND loginportal.loginPortal_id = messages.sender_id) AS query2

WHERE query1.message_id = query2.message_id;