亲爱的我有 users 表和 cars 表。
并且我有以下 join query :
select
users.id as user_id,
users.username,
users.job,
cars.id,
cars.brand as car_brand
FROM users
LEFT JOIN cars on users.id = cars.user_id
GROUP BY users.username, users.id, cars.id;
以下是快照:
如何查询拥有一辆以上汽车的用户?
我在下面尝试了代码,但返回空数据:
如何让用户拥有一辆以上的汽车? (用户名:Ismed)
答案 0 :(得分:1)
最简单,可能也是大多数性能方法是使用窗口函数:
select user_id, username, job, id, brand
from (select u.id as user_id, u.username, u.job,
c.id, c.brand as car_brand,
count(*) over (partition by u.id) as num_cars
from users u join
cars c
on u.id = c.user_id
) uc
where num_cars > 1;
请注意,我将left join
更改为join
。如果有两个匹配项,则需要一个匹配项。我还介绍了表别名,以便查询更易于编写和阅读。
答案 1 :(得分:0)
You can do in this was as well.
select
users.id as user_id,
users.username,
users.job,
cars.id,
cars.brand as car_brand
FROM users
LEFT JOIN cars on users.id = cars.user_id
where exists (select username, count(*) multiplecars
FROM users u
JOIN cars c on u.id = c.user_id
where users.username = u.username
group by
u.username
having count(*) > 1 )
如果用户拥有多于一辆汽车(即使是同一品牌,那么这将带来那些记录),如果您只希望拥有多于一种品牌护理的用户,您可以计算(不同)
答案 2 :(得分:0)
SELECT users.username 来自用户 在哪里users.id IN( 选择 users.id 来自用户 在users.id = cars.user_id上加入汽车 GROUP BY users.id 拥有计数(*)> 1 );
首先过滤拥有多于一辆汽车的用户,然后获取相应的详细信息