简体   繁体   English

MySQL 左连接子查询 *

[英]MySQL Left Join Subquery with *

I'm putting together a fairly simple query with a subquery in the JOIN statement.我正在将一个相当简单的查询与 JOIN 语句中的子查询放在一起。 It only works if I include an * in the subquery select.仅当我在子查询选择中包含 * 时才有效。 Why?为什么?

This works这有效

$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';

This doesn't这不

$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';

Should I even be doing it this way?我应该这样做吗? I thought * was not best if you don't need all the fields?如果您不需要所有字段,我认为 * 不是最好的?

try this (if I understood your intent correctly, that you wanted to filter on type_id not null):试试这个(如果我正确理解你的意图,你想过滤 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';

The explanation is that you have to select in the inner query all the fields which are referenced in the outer query.解释是您必须在内部查询中选择外部查询中引用的所有字段。

Since you want to have non-NULL values for type_id, you shouldn't be using a LEFT JOIN for it at all.由于您希望 type_id 具有非 NULL 值,因此根本不应该使用 LEFT JOIN。 You'll want the following, which uses a standard JOIN.您将需要以下使用标准 JOIN 的内容。

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

The whole point of a JOIN is that it only joins rows that actually exist. JOIN 的全部意义在于它只连接实际存在的行。 So you won't get any rows where location_hours doesn't have a corresponding location_id to locations.id.因此,您不会得到 location_hours 没有对应 location_id 到locations.id 的任何行。 Then you just filter out NULL values for location_hours.type_id.然后您只需过滤掉 location_hours.type_id 的 NULL 值。

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

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