mysql - 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 表只有一个匹配项。
解决方案
尝试以下查询:
样本数据:
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;
推荐阅读
- javascript - 如何在 vue 中使用下载属性?
- javascript - 如何为文本字段实现正则表达式以在 Extjs 中一次允许一个逗号一个空格
- python - Pandas CSV 导入中二进制变量的最佳数据类型以减少内存使用
- c - 并发线程和数据竞争
- java - Draw on Android's surfaceView
- testng - 如何在循环中多次运行具有许多测试方法的 testng 类文件
- c# - c# 后面的代码中绑定了不正确的数据
- logstash - Logstash 对 Crate DB 的支持
- tsql - How to correct this if exists query?
- yarnpkg - 运行`react-scripts`时如何查找依赖项