简体   繁体   English

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

[英]Get all results from first table in a MySQL join

I have two tables. 我有两张桌子。 I need to select all the rows (only one condition hotel_id=2) from first table and selected rows (based on condition) from 2nd table. 我需要从第一张表中选择所有行(仅一个条件hotel_id = 2),并从第二张表中选择所有行(基于条件)。 But I'm using left join only get the datas from the 2nd table. 但是我使用的左联接仅从第二张表中获取数据。

Query 询问

 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

I need to show all rooms, but now shows the common in two tables. 我需要显示所有房间,但现在在两个表中显示公共房间。

Reverse the table relationships if you want all rooms 如果要所有房间,请反转表关系

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'

But you will also need to alter the where clause as well. 但是,您还需要更改where子句。 Instead of your original where clause they can be used as part of the conditions of the join instead. 它们可以代替您的原始where子句用作连接条件的一部分。

The effect of the where clause can easily be overlooked, but if you reference a left joined table in the where clause you must also allow for the data from that table to be NULL. 可以很容易地忽略where子句的影响,但是,如果您在where子句中引用左连接表,则还必须允许该表中的数据为NULL。 eg 例如

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

If table rooms has a hotel_id then: 如果餐桌房间有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

As far as i understand you need all data from first table and only from second table which matches your where criteria. 据我了解,您需要第一张表中的所有数据,而仅第二张表中符合您的条件的数据。

 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'

According to your query the where part turns left join to inner join so you don't get all rows from first table, To solve this issue move your filters for second table in on clause, So only those records which match with the criteria will be returned from second table 根据您的查询, where部分将左联接变为内部联接,因此您不会从第一张表中获取所有行,要解决此问题,请在on子句中移动第二张表的过滤器,因此只有符合条件的记录才是从第二张表返回

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM