gpt4 book ai didi

MySQL 左连接子查询带 *

转载 作者:IT王子 更新时间:2023-10-29 00:37:09 26 4
gpt4 key购买 nike

我正在将一个相当简单的查询与 JOIN 语句中的子查询组合在一起。仅当我在子查询选择中包含 * 时才有效。为什么?

这行得通

$sql = 'SELECT locations.id, title, name, hours.lobby
FROM locations
LEFT JOIN states ON states.id = locations.state_id
LEFT JOIN (SELECT *, type_id IS NOT NULL AS lobby FROM location_hours) AS hours ON locations.id = hours.location_id
GROUP BY locations.id';

这不是

$sql = 'SELECT locations.id, title, name, hours.lobby
FROM locations
LEFT JOIN states ON states.id = locations.state_id
LEFT JOIN (SELECT type_id IS NOT NULL AS lobby FROM location_hours) AS hours ON locations.id = hours.location_id
GROUP BY locations.id';

我应该这样做吗?如果您不需要所有字段,我认为 * 不是最好的?

最佳答案

试试这个(如果我正确理解你的意图,你想过滤 type_id 不为空):

   SELECT locations.id, title, name, hours.lobby
FROM locations
LEFT JOIN states
ON states.id = locations.state_id
LEFT JOIN (SELECT location_id, type_id AS lobby
FROM location_hours
WHERE type_id IS NOT NULL) AS hours
ON locations.id = hours.location_id
GROUP BY locations.id';

解释是您必须在内部查询中选择外部查询中引用的所有字段。

关于MySQL 左连接子查询带 *,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19553963/

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