php sql左连接多个值

bhmjp9jg  于 2021-06-18  发布在  Mysql
关注(0)|答案(2)|浏览(283)

我一直在玩,试图找到一个解决办法,但有点卡住了。
我有一个'meetings'表,表中有两列,其中包含来自'members'的id,我需要在会议列表中显示成员详细信息。
我试过了,但没用。。。

$q = "SELECT (meetings.id) AS meetings_id, meetings.columnA, meetings.ColumnB, (members.id) AS members_id, members.first, members.last FROM meetings**LEFT JOIN members ON meetings.columnA = members.id AND meetings.columnB = members.id**";
$r = mysqli_query($dbc, $q);
while($row = mysqli_fetch_assoc($r)) { }

如果只对单个值(columna或columnb)进行连接,我只能让它工作,但这显然只检索单个成员的数据。
虽然这种方法可行,但并不理想。。。

$q = "SELECT * FROM meetings";
$r = mysqli_query($dbc, $q);
while($row = mysqli_fetch_assoc($r)) { 
    $qm = "SELECT * FROM members WHERE id = '$row[columnA]'";
    $rm = mysqli_query($dbc, $qm);
    while($rowm = mysqli_fetch_assoc($rm)) {
        if  ($row['columnA'] == $rowm['id']) { echo $rowm['first']; }
    }
    $qm = "SELECT * FROM members WHERE id = '$row[columnB]'";
    $rm = mysqli_query($dbc, $qm);
    while($rowm = mysqli_fetch_assoc($rm)) { 
        if  ($row['columnB'] == $rowm['id']) { echo $rowm['first']; }
    }
}

有没有一种方法可以让连接工作,或者更好的方法,这样我只需要进行一个查询?
谢谢。

j8ag8udp

j8ag8udp1#

我想你只想要两个 left join s。

SELECT m.id AS meetings_id, m.columnA, m.ColumnB,
       me1.id AS members_id, me1.first, me1.last,
       me2.id AS members_id, me2.first, me2.last
FROM meetings m LEFT JOIN 
     members me1
     ON m.columnA = me1.id LEFT JOIN
     members me2
     ON me.columnB = me2.id;
fkvaft9z

fkvaft9z2#

试试这个:

SELECT 
meetings.id AS meetings_id, 
meetings.columnA, 
meetings.ColumnB, 
members.id AS members_id, 
CONCAT(m1.first,' ',m1.last) as  columnA_Member
CONCAT(m2.first,' ',m2.last) as  columnB_Member
FROM 
    meetings 
INNER JOIN 
    members as m1 ON meetings.columnA = m1.id
INNER JOIN 
    members as m2 ON meetings.columnB = m2.id

相关问题