我有以下2张桌子:
CREATE TABLE owner (
id INT NOT NULL,
first_name VARCHAR(20) NOT NULL,
last_name VARCHAR(20) NOT NULL,
PRIMARY KEY (id)
);
CREATE TABLE vehicle (
id INT NOT NULL,
owner_id INT NOT NULL, -- Foreign key to the owner table
name VARCHAR(20) NOT NULL,
color VARCHAR(20) DEFAULT NULL,
PRIMARY KEY (id)
);
我正在尝试编写一个查询,以查找所有拥有黑色车辆的所有者的姓氏和名字,并按姓氏对所有者进行排序,并且如果同一所有者多次拥有颜色车辆,则仅显示一次名称。
select first_name, last_name, count(v.id)
from owner o join vehicle v on o.id = v.owner_id
where color = 'black'
group by first_name, last_name
order by last_name;
在这里,我该如何避免车辆数,然后再获得唯一名称(first_name,last_name),并按last_name排序结果。
答案 0 :(得分:5)
一种可以说是更优雅的解决方案是使用exists
运算符而不是加入:
SELECT first_name, last_name
FROM owner o
WHERE EXISTS (SELECT *
FROM vehicle v
WHERE v.color = 'black' AND o.id = v.owner_id)
ORDER BY last_name ASC
答案 1 :(得分:3)
使用DISTINCT
运算符:
select DISTINCT first_name, last_name
from owner o join vehicle v
on o.id = v.owner_id
where LOWER(color) = 'black'
order by last_name;
我也将其更改为寻找'black'
,不管它是大写,小写还是大小写。
好运。