mysqli查询用两个唯一键连接

时间:2015-04-19 06:03:43

标签: php mysql mysqli

你好,我在我的网页上有这个查询

 $otherupdates=mysqli_query
($conn,"
    SELECT f.sender,f.receiver,f.field,m.name 
    FROM friend f,members m
    WHERE ((f.sender IN ($variable) OR f.receiver IN ($variable)) 
    AND ( f.field='friends' || f.field='fan') 
    AND ( f.date > '$adatevariable' AND f.sender=m.id)) 
    ORDER BY date DESC LIMIT 16"
);

$variable="'1','2','3'......"; // not important
$adatevariable=date('d', strtotime($today . ' - 2 day'));// not imp

这个查询的作用是,获取与where子句匹配的所有行,并且还获取发送者的名称(f.sender = m.id),但我也想通过此查询获取接收者的名称,我不需要另一个问题..

这可能请帮助

1 个答案:

答案 0 :(得分:1)

如果您将查询更改为:

select 
    f.sender,
    f.receiver,
    f.field,
    senders.name AS sender_name,
    recievers.name AS recievers_name
from 
    friend f
    INNER JOIN members senders ON f.sender=senders.id
    INNER JOIN members recievers ON f.receiver = recievers.id
where 
    (f.sender IN ($variable) or f.receiver IN ($variable)) 
    and f.field IN ('friends', 'fan') 
    and f.date > '$adatevariable'
order by 
    date desc 
limit 16

这样做可以让您访问members表两次,一次为senders,另一次为recievers。将这些内容与friendsender字段上的reciever表相关联,senders将包含发件人的所有信息,recievers将包含所有信息在收货人身上。