我想在一个简单的查询中结合两个单独的查询。我怎么能这样做?
查询:
select idProduct, date,price from products where idProduct like 'Prod01'
idProduct Date Price
Pro01 2014-05-29 19.1
Pro01 2014-05-29 18.8
Pro01 2014-05-29 18.7
Pro01 2014-05-29 18.9
Pro01 2014-05-29 18.7
Pro01 2014-05-29 18.5
select idProduct, date,price from products where idProduct like 'Prod02'
idProduct Date Price
Pro02 2014-05-29 29.1
Pro02 2014-05-29 28.8
Pro02 2014-05-29 28.7
Pro02 2014-05-29 28.9
Pro02 2014-05-29 28.7
Pro02 2014-05-29 28.5
我想要降低产品的价格' Prod02'在第四栏。
我解释得很好吗?
基本上我需要这样的东西:
idProduct Date Price of 'Prod01' Price of 'Prod02'
Pro01 / Pro02 2014-05-29 19.1 28.1
Pro01 / Pro02 2014-05-29 18.8 26.1
Pro01 / Pro02 2014-05-29 18.7 24.1
Pro01 / Pro02 2014-05-29 18.9 22.1
Pro01 / Pro02 2014-05-29 18.7 21.1
Pro01 / Pro02 2014-05-29 18.5 22.1
答案 0 :(得分:1)
SELECT *
FROM(
SELECT idProduct, Date,(Price) as Price01, '0' as Price02
FROM products
WHERE idProduct LIKE 'Prod01'
UNION
SELECT idProduct, Date,'0' as Price01, (Price) as Price02
FROM products
WHERE idProduct like 'Prod02'
) as temp
答案 1 :(得分:0)
如果日期列中有不同的时间戳,可以使用JOIN
来获取数据(每行只包含日期,并且总是相同但不起作用)
SELECT concat(p1.idProduct, ' / ', p2.idProduct) idProduct
, p1.`Date`
, p1.`Price` as `Price of Prod01`
, p2.`Price` as `Price of Prod02`
FROM (SELECT idProduct, Date, Price
FROM products
WHERE idProduct LIKE 'Pro01') p1
LEFT JOIN (SELECT idProduct, Date, Price
FROM products
WHERE idProduct LIKE 'Pro02') p2
ON p1.Date = p2.Date
如果两个产品的行要以相同的顺序(哪个顺序?),你可以使用MySQL版本的Row_Number
SELECT concat(p1.idProduct, ' / ', p2.idProduct) idProduct
, p1.`Date` `Date of Prod01`
, p2.`Date` `Date of Prod02`
, p1.`Price` as `Price of Prod01`
, p2.`Price` as `Price of Prod02`
FROM (SELECT idProduct, Date, Price
, @rownum := @rownum + 1 AS ID
FROM products,
(SELECT @rownum := 0) r
WHERE idProduct LIKE 'Pro01') p1
LEFT JOIN (SELECT idProduct, Date, Price
, @rownum2 := @rownum2 + 1 AS ID
FROM products,
(SELECT @rownum2 := 0) r
WHERE idProduct LIKE 'Pro02') p2
ON p1.ID = p2.ID
但我真的希望你的时间戳不仅仅是日期。