使用 MySQL 替代 GROUP BY/HAVING
Alternatives to GROUP BY/HAVING using MySQL
我遇到了以下问题:
Come up with a query that lists the people(pname) who own more than one car (you cannot use GROUP BY and/or HAVING)
Use the following database schema:
vehicle (licplate*, year, make, model, cost, pname)
这是我想使用的查询
select pname from vehicle
group by pname
having count(*) > 1;
我一直在尝试根据规范想出一种方法来执行此操作,但我没有取得任何成功。有人可以指导我完成此操作的逻辑吗?
感谢您的阅读。
您尝试过使用 Subquery 吗?
以你的table为参考,应该是这样的
SELECT
p.pname
FROM person AS p
WHERE
(SELECT count(*) FROM vehicle where pname = p.pname) > 1
select * from
(select *,
if (@name= pname, 1,0) as flag,
@name:= pname as pn
from vehicle
order by pname) sub
where sub.flag=1;
我们还可以添加 DISTINCT 来涵盖超过 2 辆汽车的情况
更新:
Select *
from vehicle v1
join vehicle v2 on v1.pname=v2.pname
and (v1.id!=v2.id)
而不是 v1.id!=v2.id 您可以添加主键检查 v1 的 PK !=v2 的 PK
我遇到了以下问题:
Come up with a query that lists the people(pname) who own more than one car (you cannot use GROUP BY and/or HAVING)
Use the following database schema:
vehicle (licplate*, year, make, model, cost, pname)
这是我想使用的查询
select pname from vehicle
group by pname
having count(*) > 1;
我一直在尝试根据规范想出一种方法来执行此操作,但我没有取得任何成功。有人可以指导我完成此操作的逻辑吗?
感谢您的阅读。
您尝试过使用 Subquery 吗?
以你的table为参考,应该是这样的
SELECT
p.pname
FROM person AS p
WHERE
(SELECT count(*) FROM vehicle where pname = p.pname) > 1
select * from
(select *,
if (@name= pname, 1,0) as flag,
@name:= pname as pn
from vehicle
order by pname) sub
where sub.flag=1;
我们还可以添加 DISTINCT 来涵盖超过 2 辆汽车的情况
更新:
Select *
from vehicle v1
join vehicle v2 on v1.pname=v2.pname
and (v1.id!=v2.id)
而不是 v1.id!=v2.id 您可以添加主键检查 v1 的 PK !=v2 的 PK