gpt4 book ai didi

postgresql - 有条件地从oneToMany中选择

转载 作者:行者123 更新时间:2023-11-29 13:38:27 25 4
gpt4 key购买 nike

如果没有以原价选择它,我会尝试在有报价时从商品表中选择商品。为此,我有 2 个表 items 和 priceList,这是一个例子:

| itemId | itemName      | 
|--------|---------------|
| 1 | bikex1 |
| 2 | bikex2 |
| 3 | bikex3 |
| 4 | bikex4 |


| priceIDId | itemID | itemPrice | priceStatus |
|-----------|----------|-----------|-------------|
| 1 | 1 |100 | offer |
| 2 | 1 |150 | orignalPrice|
| 4 | 2 |200 | orignalPrice|

因为 bikex2 没有报价,我将获得原始价格 (200),但对于 bikex1,我将获得报价 (100)

| priceIDId | itemID   | itemPrice | priceStatus |
|-----------|----------|-----------|-------------|
| 1 | 1 |100 | offer |
| 4 | 2 |200 | orignalPrice|

我试过的代码如下:

select * from priceList where priceStatus = 'offer' union all select * from priceList where priceStatus = 'orignalPrice' AND  NOT EXISTS (select * from priceList where priceStatus = 'offer')

最佳答案

你可以左连接两次:

select 
i.*,
coalesce(p1.itemPrice, p2.itemPrice) itemPrice,
coalesce(p1.priceStatus, p2.priceStatus) priceStatus
from items i
left join priceList p1 on p1.itemID = i.itemID and p1.priceStatus = 'offer'
left join priceList p2 on p2.itemID = i.itemID and p1.priceStatus = 'originalPrice'
where coalesce(p1.itemID , p2.itemID) is not null -- at least one of the joins should match

另一种选择是使用带条件排序的窗口函数:

select itemID, itemName, itemPrice, priceStatus
from (
select
i.*,
p.itemPrice,
p.priceStatus,
row_number() over(
partition by p.itemID
order by case when p.priceStatus = 'offer' then 0 else 1
end) rn
from items i
inner join priceList p on p.itemID = i.itemID
) t
where rn = 1

关于postgresql - 有条件地从oneToMany中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58952507/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com