Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/75.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Mysql 将左联接与GROUP BY组合,同时还包括NULL_Mysql_Sql_Group By_Left Join - Fatal编程技术网

Mysql 将左联接与GROUP BY组合,同时还包括NULL

Mysql 将左联接与GROUP BY组合,同时还包括NULL,mysql,sql,group-by,left-join,Mysql,Sql,Group By,Left Join,使用左连接和分组方式组合具有一对多映射的表时遇到问题 我有一个唯一ID的下表(在示例中,这是house_编号) 房屋: |house_number| bedrooms| |0 | 4 | |1 | 3 | |2 | 1 | 我想使用唯一ID与第二个表左连接,其中第二个表可能有也可能没有每个唯一ID的多个条目。例如 居住者: | house_number | occupant_id | type

使用左连接和分组方式组合具有一对多映射的表时遇到问题

我有一个唯一ID的下表(在示例中,这是house_编号)

房屋:

|house_number| bedrooms|
|0           | 4       |
|1           | 3       |
|2           | 1       |
我想使用唯一ID与第二个表左连接,其中第二个表可能有也可能没有每个唯一ID的多个条目。例如

居住者:

| house_number | occupant_id | type    |
| 0            | 3           | 19      |
| 0            | 1           | 20      |
| 0            | 2           | 21      |
| 2            | 7           | 20      |
现在,我想要实现的是每个门牌号只输入一个门牌,但在左键中优先选择20类的住户,同时保留那些没有列出任何住户的房屋,例如

|house_number| bedrooms| occupant_id | type    |
|0           | 4       | 1           | 20      |
|1           | 3       | null        | null    |
|2           | 1       | 7           | 20      |
我可以使用GROUP BY来实现每间房子只有一个入口,但是,我需要确保随它返回的乘员行(如果存在)具有
type=20

如果我只是使用一个
WHERE(type=20)
,那么我就不会得到house\u number=1的条目


如何实现这个最终的表?

试试
在哪里(type=20或type为null)
条件怎么样?

试试
在哪里(type=20或type为null)
条件怎么样

SELECT h.house_number,h.bedrooms
        , o.occupant_id,o.ztype
FROM houses h
LEFT JOIN occupants o ON h.house_number = o.house_number
        AND o.ztype =20
        ;
顺便说一句,我不得不将“type”替换为“ztype”,因为type在Postgres中是一个保留字


顺便说一句,我不得不用“ztype”替换“type”,因为type在Postgres中是一个保留字。

尝试使用WHERE(type=20或type为NULL)来保留外部联接,在ON子句中过滤右表。尝试使用WHERE(type=20或type为NULL)来保留外部联接,在ON子句中过滤右表。