我有一张桌子,列出了供应牛肉鸡肉的餐厅,与此类似:
Res Meat
res1 chicken
res1 chicken
res1 beef
res2 chicken
res2 chicken
res3 beef
我正在尝试编写一个查询,返回哪些餐厅只提供鸡肉或牛肉,而不是两者都提供,而不消除结果中的重复项。
试试这个:
CREATE TABLE rest
(
id int auto_increment primary key,
Res varchar(20),
Meat varchar(20)
);
INSERT INTO rest
(Res,Meat)
VALUES
('res1','chicken'),
('res1', 'chicken'),
('res1', 'beef'),
("res2", 'chicken'),
("res2", 'chicken'),
( 'res3', 'beef' )
select Res from
(select distinct Res,Meat from rest ) test
group by Res
having count(1) = 1
试试这个方法:
create table tab
(
Res varchar(10),
Meat varchar(10)
)
insert into tab ( Res, Meat ) values ( 'res1', 'chicken' )
insert into tab ( Res, Meat ) values ( 'res1', 'chicken' )
insert into tab ( Res, Meat ) values ( 'res1', 'beef' )
insert into tab ( Res, Meat ) values ( 'res2', 'chicken' )
insert into tab ( Res, Meat ) values ( 'res2', 'chicken' )
insert into tab ( Res, Meat ) values ( 'res3', 'beef' )
select Res
from (
select distinct Res,Meat
from tab ) T
group by Res
having count(1) = 1
您可以使用 except 运算符
select * from table
where meat = 'chicken' or meat = 'Beer'
except
select * from table
where meat = 'chicken' and meat = 'Beer'
尝试:
select Res
from rest
group by Res
having count(distinct Meat) = 1