示例ps表col:
-------------------------------------------------------
id, price, start, end, priority
===========================
p1, 100, feb1, feb2, 1
------------------------------------------------
p1, 200, feb3, feb5, 2
------------------------------------------------
p2, 10, jan1, jan2, 1
-------------------------------------------------
p2, 20, mar1, mar3, 2
此查询将这些列设为o / p:id,promo_price,special_price。
select p.id,
(select ps1.price from ps ps1 where p.id=ps1.id and ps1.priority=1) as promo_price,
(select ps1.price from ps ps1 where p.id=ps1.id and ps1.priority=2) as special_price
from p where p.id = p1
但我还需要相应的开始和结束日期: ID,promo_price,special_price,开始,结束
当我将开始/结束列添加到子查询时,它会抛出一个错误: 操作数应包含1列
有没有办法在子查询中提取日期列。
答案 0 :(得分:0)
select p.id,
ps1.price as promo_price,
ps2.price as special_price,
...other columns from ps1, ps2
from p
left join ps ps1 on p.id=ps1.id and ps1.priority=1
left join ps ps2 on p.id=ps2.id and ps2.priority=2
where p.id = p1
答案 1 :(得分:0)
最简单的方法可能是将内部查询用作表格式结构,并使用join
:
SELECT p.id, promo.*, special.*
FROM p
JOIN (SELECT ps.*
FROM ps
WHERE ps.priority = 1) promo ON p.id = promo.id
JOIN (SELECT ps.*
FROM ps
WHERE ps.priority = 2) special ON p.id = special.id
WHERE p.id = 'p1'
答案 2 :(得分:0)
(选择id,price,'promo'作为typ,start,end from room.ps1,其中priority = 2) 联盟 (选择id,price,'Special'作为typ,start,end from room.ps1,其中priority = 1)
这是获得促销价,特价,开始,结束的唯一方式,因为两个条目的开始日期和结束日期不相等。
否则你可以拥有
从中选择a.id,promo,promo_dates,special,special_dates (选择id,价格作为促销,concat(开始,'到',结束)作为promo_dates from room.ps1,其中priority = 2)作为左连接 (选择id,价格为Special,concat(start,'to',end)as special_dates from room.ps1 where priority = 1)as b using using(id);
让所有人都在一行