我想加入表格。条件是我只想加入只有一行要匹配的那些行。例如。
书籍:
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表只有一个匹配项。
答案 0 :(得分:0)
尝试以下查询:
样本数据:
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;
答案 1 :(得分:0)
您可以使用书的自连接表来选择只有一个匹配项的书
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
答案 2 :(得分:0)
如果要避免在必须使用自联接的地方嵌套查询,则可以使用MySQL 8.0.11的窗口函数,正是这种情况适用于此类情况