gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-29 03:55:50 30 4
gpt4 key购买 nike

我有两张 table 。我需要从第一个表中选择所有行(只有一个条件 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

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

最佳答案

如果你想要所有房间,反转表关系

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。例如

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

如果 table rooms 有一个 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

关于php - 从 MySQL 连接中的第一个表中获取所有结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47830521/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com