MySQL-如果没有重复,则加入
我想加入这张桌子。条件是我只想连接那些只有一行要匹配的行。例如 书籍:MySQL-如果没有重复,则加入,mysql,join,Mysql,Join,我想加入这张桌子。条件是我只想连接那些只有一行要匹配的行。例如 书籍: id | name | price 1 | book1 | 19 2 | book2 | 19 3 | book3 | 30 报价: id | offer | price 1 | offer1 | 19 2 | offer2 | 30 现在,如果我在这些表上选择查询: SELECT * FROM price_offer JOIN books ON price_offer.price = books.
id | name | price
1 | book1 | 19
2 | book2 | 19
3 | book3 | 30
报价:
id | offer | price
1 | offer1 | 19
2 | offer2 | 30
现在,如果我在这些表上选择查询:
SELECT * FROM price_offer
JOIN books ON price_offer.price = books.price
我只想加入id为3的book,因为它与price\u 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;
您可以使用books表的自联接来选择只有一个匹配项的书籍
select po.*, b1.*
from price_offer po
join books b1 on po.price = b1.price
join (
select price,max(id) id
from books
group by price
having count(*) = 1
) b2 on b1.id = b2.id
如果您想避免将查询嵌套在必须使用自联接的地方,可以使用MySQL 8.0.11的窗口函数,这正是针对这种情况的