如何根据条件合并 2 个表但 select 值?

how to union 2 tables but select values based on condition?

有 2 tables - 书籍,用品。 供应 table:

supply_id title author price amount
1 title1 author1 518.99 2
2 title2 author2 570.20 6
3 title3 author3 540.50 7
4 title4 author4 360.80 3

这本书 table:

book_id title author price amount
1 Мастер и Маргарита Булгаков М.А. 670.99 3
2 Белая гвардия Булгаков М.А. 540.50 5
3 Идиот Достоевский Ф.М. 460.00 10
4 Братья Карамазовы Достоевский Ф.М. 799.01 3
5 Игрок Достоевский Ф.М. 480.50 10
6 Стихотворения и поэмы Есенин С.А. 650.00 15

我需要合并它们,但只有 select 那些价格较高的行。

select title, price, amount 
from supply  a1
union all
select title, price, amount 
from book a2
where a1.price > a2.price

您可以使用 window 函数:

select bs.*
from (select bs.*,
             row_number() over (partition by title order by price desc) as seqnum
      from ((select supply_id, title, author, price, amount
             from book
            ) union all
            (select supply_id, title, author, price, amount
             from supply
            )
           ) bs
     ) bs
where seqnum = 1;
      

试试这个:

select title, price, amount 
from supply s
where not exists (select 1 from book b where s.title = b.title and b.price > s.price)

union all

select title, price, amount 
from book b
where not exists (select 1 from supply s where s.title = b.title and s.price > b.price)