我有两个表Sell和Purchase。我的查询给了我想要的结果,我对它的性能非常谨慎,因此请更好地指导我。我的表是:
表卖
UserId | ProductId | ProductName | ProductPrice
1 | p_101 | Cycle | 500
1 | p_121 | Car | 500000
2 | p_111 | Cycle | 5000
表购买
UserId | ProductId | ProductName | ProductPrice
1 | p_109 | CellPhone | 150
2 | p_121 | Car | 500000
3 | p_111 | Book | 15
所需的输出表
Type | ProductId | ProductName | ProductPrice
Sell | p_101 | Cycle | 500
Sell | p_121 | Car | 500000
Purchase| p_109 | CellPhone | 150
工作查询:
SELECT type, P1.ProductId, P1.ProductName, P1.ProductPrice
FROM
(
SELECT s.UserId, 'Sell' as type, s.ProductId, s.ProductName, s.ProductPrice FROM [Sell] s
UNION
SELECT p.userid, 'Purchase' as type, p.ProductId, p.ProductName, p.ProductPrice FROM [Purchase] p
) as P1
WHERE userid=1
更好的设计是合并两个表并具有transaction_type列,该列将以“ Purchase”或“ Sell”作为值。如果这样做,则不必做UNION或UNION ALL。
对于当前的设计,这里是一种获取记录的简单快捷的方法。请注意,由于UNION对唯一记录使用DISTINCT,因此我使用UNION ALL的速度比UNION快,我认为这种情况不适用于您的情况。如果您提供有关索引和执行计划的详细信息,我可以看看是否有更好的方法。
SELECT s.userid,
'Sell' as type,
s.ProductId,
s.ProductName,
s.ProductPrice
FROM Sell s
WHERE UserId = 1
UNION ALL
SELECT p.userid,
'Purchase' as type,
p.ProductId,
p.ProductName,
p.ProductPrice
FROM Purchase P
WHERE UserId = 1
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句