一个很多查询,其中许多人有一个记录

时间:2017-07-28 09:08:45

标签: mysql one-to-many relation

我有用户表,它有很多属性。具有一对多关系的用户表。我尝试选择属性表中只有一个属性的用户

select *, count(p.account_id) as c
form accounts as a
left join properties as p on a.account_id = p.account_id
group by p.account_id
having c = 1 

但这似乎不起作用

2 个答案:

答案 0 :(得分:1)

您也可以将其作为第二个请求:

select * 
from (
    SELECT *, p.account_id , count(*) as num 
    from accounts as a 
    INNER JOIN properties as p ON a.account_id = p.account_id 
    group by p.account_id 
) query
where query.num = 1

答案 1 :(得分:0)

SELECT *, count(*) as num from 
accounts as a INNER JOIN properties as p 
ON a.account_id = p.account_id 
group by p.account_id 
having num=1