从MySQL连接中的第一个表中获取所有结果

时间:2017-12-15 10:37:11

标签: php mysql

我有两张桌子。我需要从第一个表中选择所有行(只有一个条件hotel_id = 2),从第二个表中选择所选行(基于条件)。但是我使用左连接只能从第二个表中获取数据。

查询

 SELECT R.name room_name,
        R.id room_id,
        UD.discount 
   FROM user_discounts UD 
   LEFT 
   JOIN rooms R 
     ON R.id = UD.room_id
  WHERE UD.user_id = 1482
    AND UD.hotel_id = 2

我需要显示所有房间,但现在在两个表中显示共同点。

2 个答案:

答案 0 :(得分:4)

如果您想要所有房间

,请反转表格关系
SELECT `R`.`name` as `room_name`, `R`.`id` as `room_id`, `UD`.`discount` as `discount`
FROM  `rooms` as `R`
LEFT JOIN `user_discounts` as `UD` ON `R`.`id`= `UD`.`room_id`
             AND`UD`.`user_id` = '1482'
             AND `UD`.`hotel_id` = '2'

但是你也需要改变where子句。而不是你原来的where子句,它们可以用作连接条件的一部分。

很容易忽略where子句的效果,但如果在where子句中引用左连接表,则还必须允许该表中的数据为NULL。 e.g

SELECT `R`.`name` as `room_name`, `R`.`id` as `room_id`, `UD`.`discount` as `discount`
FROM  `rooms` as `R`
LEFT JOIN `user_discounts` as `UD` ON `R`.`id`= `UD`.`room_id`
WHERE (`UD`.`user_id` = '1482'
   AND `UD`.`hotel_id` = '2'
      )
   OR `UD`.`room_id` IS NULL

如果餐厅有hotel_id,那么:

SELECT `R`.`name` as `room_name`, `R`.`id` as `room_id`, `UD`.`discount` as `discount`
FROM  `rooms` as `R`
LEFT JOIN `user_discounts` as `UD` ON `R`.`id`= `UD`.`room_id`
             AND`UD`.`user_id` = '1482'
             AND `UD`.`hotel_id` = `R`.`hotel_id`
WHERE `R`.`hotel_id` = 2

答案 1 :(得分:3)

据我了解,您需要第一张表格中的所有数据,并且只需要符合您的标准的第二张表格。

 SELECT `R`.`name` as `room_name`, `R`.`id` as `room_id`, `UD`.`discount` as `discount`
 FROM `rooms` as `R`
 LEFT JOIN `user_discounts` as `UD`  ON `R`.`id`= `UD`.`room_id`
 AND `UD`.`user_id` = '1482'
 AND `UD`.`hotel_id` = '2'

根据您的查询,where部分将左连接转为内连接,因此您无法从第一个表中获取所有行。要解决此问题,请在on子句中移动第二个表的过滤器,因此,只有那些符合条件的记录才会从第二个表中返回