我在MySQL表中有一对一的关系。
房屋可以有很多业主。
我想列出一所房子的所有业主。
我试过这个:
SELECT id, name, address
,(
SELECT CONCAT(firstname)
FROM owners
WHERE houses_id = houses.id
) AS 'owner_firstname'
FROM houses;
但我得到了这个结果
Error Code: 1242
Subquery returns more than 1 row
我希望得到像这样的结果
100 | Liberty House | 200, NY Street | me, myself, Iren
由于
答案 0 :(得分:4)
要解决您的错误:您的选择的子查询带回了多个所有者。在您的情况下,查询需要返回一个文字列表。您可以使用GROUP_CONCAT()函数在MySQL中实现此功能,以组合特定房屋的所有者名称:
SELECT h.id, h.name, h.address, GROUP_CONCAT(o.firstname) AS owner_firstname
FROM houses AS h
INNER JOIN owners AS o ON h.id = o.houses_id
GROUP BY h.id, h.name, h.address
答案 1 :(得分:1)
我认为您正在寻找group_concat
:
select id, name, address,
(select group_concat(firstname separator ', ')
from owners where houses_id = houses.id) as 'owner_firstname'
from houses;