使用左连接语法SQL

时间:2016-02-26 14:59:36

标签: mysql left-join

我有3张桌子:

**user**
idnumber | fullname
2015-01    sample doe

**Equipment**
id | Equipment
1     mic
2    Extension

**Reservation_list**
id | idnumber | reserve_slot | description | equip_id |
1    2015-011       1           sample         1
2    2015-011       2           sample2        2


**reservation slots**
id | reservation_int | reservation_out
 1     10:00               12:00
 2     1:00                2:00

我在这里得到了这个号码:

index.php?idnumber=?2015-011

$idnumber = $_GET['idnumber'];

如何才能得到这样的结果:(正如你可以看到2个表加入reservation_list和reservation_slots

reservation_int | reservation_out | description | equipment |
    10:00               12:00          sample      mic
     1:00                2:00          sample2    extension

如您所见,它显示“2015-011”的所有记录。

2 个答案:

答案 0 :(得分:2)

我不确定你在这里需要LEFT JOIN。一个简单的INNER JOIN将更有效率,并为您提供所需的一切:

SELECT
    RS.reservation_int,
    RS.reservation_out,
    RL.description
FROM
    user
    INNER JOIN Reservation_List RL ON user.idnumber = RL.idnumber
    INNER OUTER JOIN Reservation_Slots RS ON RL.ID = RS.ID
WHERE user.idnumber = '2015-011'

如果您的要求已更改,并且您需要列出有关user的信息以及任何预订类型信息(如果可用)。然后你可以切换到LEFT OUTER JOIN

答案 1 :(得分:0)

SELECT R1.description,
       R2.reservation_int,
       R2.reservation_out 
  FROM user AS u 
    INNER JOIN reservation_List AS R1 ON (u.idnumber = R1.idnumber) 
    INNER JOIN equipment as E ON(E.id = R1.equip_id)
    INNER JOIN reservation_slots AS R2  ON(R1.reserve_slot = R2.id) 
  WHERE u.idnumber = "2015-011"