我有这两个表:
Name | Income
----------|----------
Alice | 200
Bob | 100
Charlie | 50
Dave | 500
Name | Outcome
----------|----------
Alice | 300
Bob | 40
Charlie | 100
Dave | 250
我可以进行此查询以获取所有收入大于150的人并订购
SELECT Name, Income
FROM table1
WHERE Income > 150
ORDER BY Income DESC
同样地,我可以得到所有结果低于200的人:
SELECT Name, Outcome
FROM table2
WHERE Outcome < 200
ORDER BY Outcome DESC
有没有办法通过编写单个查询来获取两个视图,即只使用一个;
?
Name | Income
----------|----------
Dave | 500
Alice | 200
Name | Outcome
----------|----------
Charlie | 100
Bob | 40
我知道JOIN
,但结果只会产生一个表。我不能使用UNION
因为结果和收入确实具有相同的数据类型,但它们意味着不同的东西。
答案 0 :(得分:0)
你可以JOIN
这两个表按名称和SELECT
收入和结果,例如:
SELECT t1.name, t1.Income, t2.Outcome
FROM table1 t1 JOIN table2 t2 ON t1.Name = t2.Name
WHERE t1.Income > 150 AND t2.Outcome < 200
ORDER BY t1.Income DESC t2.Outcome DESC;
更新(根据相关编辑)
您不能在两个单独的输出上生成一个查询。最接近你可以使用UNION
和另一列来区分输出,例如:
SELECT Name, Income, 'Income'
FROM table1
WHERE Income > 150
ORDER BY Income DESC
UNION
SELECT Name, Outcome, 'Outcome'
FROM table2
WHERE Outcome < 200
ORDER BY Outcome DESC
答案 1 :(得分:0)
您展示的内容仍然是两个单独的结果。一个查询给你一个结果。如果要组合提供一个查询和一个结果的两个查询。一种方法:
SELECT what, name, value
FROM
(
SELECT 'INCOME' as what, name, income as value, 1 as sortkey1, -income as sortkey2
FROM table1
WHERE income > 150
UNION ALL
SELECT 'OUTCOME' as what, name, outcome as value, 2 as sortkey1, outcome as sortkey2
FROM table2
WHERE outcome < 200
)
ORDER BY sortkey1, sortkey2;