PHP SQL LEFT JOIN多个值

时间:2018-11-01 13:22:54

标签: php mysql sql left-join

我一直在玩耍,试图找到一个解决方案,但是有点卡住了。

我有一个“会议”表,其中有两列,其中包含来自“成员”的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']; }
    }
}

是否有办法使JOIN正常工作或更有效,所以我只需要进行单个查询?

谢谢。

2 个答案:

答案 0 :(得分:1)

尝试一下::

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

答案 1 :(得分:1)

我认为您只需要两个memset()

left join