首页 > 解决方案 > MySQL - 如果没有重复则加入

问题描述

我想加入餐桌。条件是我只想加入那些只有一行匹配的行。例如。

图书:

id | name   | price
1  | book1  | 19
2  | book2  | 19
3  | book3  | 30

price_offer:

id | offer  | price
 1 | offer1 | 19
 2 | offer2 | 30

所以现在如果我在这些表上选择查询:

SELECT * FROM price_offer
JOIN books ON price_offer.price = books.price

我只想加入 id 为 3 的书,因为它与 price_offer 表只有一个匹配项。

标签: mysqljoin

解决方案


尝试以下查询:

样本数据:

create table books(id int, name varchar(10), price int);
insert into books values
(1, 'book1', 19),
(2, 'book2', 19),
(3, 'book3', 30);

create table price_offer(id int, offer  varchar(10), price int);
insert into price_offer values
(1, 'offer1', 19),
(2, 'offer2', 30);

询问:

select max(b.id)
from price_offer p 
left join books b on b.price = p.price
where p.id is not null
group by b.price
having count(*) = 1;

推荐阅读