如何在MySQL中的同一个表上使用join来组合这两个查询?

时间:2017-12-30 06:29:31

标签: mysql

SELECT MAX(property_price) AS LargestSalePrice
     , MIN(property_price) AS LowestSalePrice 
  FROM property_listings 
 WHERE property_intent = 'Sale' 

SELECT MAX(property_price) AS LargestRentPrice
     , MIN(property_price) AS LowestRentPrice 
  FROM property_listings 
 WHERE property_intent = 'Rent'

4 个答案:

答案 0 :(得分:2)

我做这样的事情。

SELECT MAX(property_price) as MaxPrice, 
 MIN(property_price) as MinPrice, 
 property_intent 
FROM property_listings
WHERE property_intent IN('Rent','Sale')
GROUP BY property_intent;

它会改变您的输出,但是更好,因为不需要为最小和最大价格硬编码不同的结果字段名称。这更多地按照预期使用SQL - 结果包括property_intent,因此当您处理结果时,您知道哪个是哪个并且可以从那里进一步查找。如果您想添加其他property_intent值,只需删除WHERE即可获得完整报告。

http://sqlfiddle.com/#!9/1a0cd4/1

答案 1 :(得分:1)

使用嵌套查询:

SELECT *
FROM (SELECT MAX(property_price) AS LargestSalePrice, MIN(property_price) AS LowestSalePrice 
      FROM property_listings WHERE property_intent = 'Sale') as Sale,
     (SELECT MAX(property_price) AS LargestRentPrice, MIN(property_price) AS LowestRentPrice 
      FROM property_listings WHERE property_intent = 'Rent') as Rent

答案 2 :(得分:0)

这肯定有用:

SELECT MAX(property_price) AS LargestSalePrice, MIN(property_price) AS LowestSalePrice FROM property_listings WHERE property_intent = 'Sale'

UNION

SELECT MAX(property_price) AS LargestRentPrice, MIN(property_price) AS LowestRentPrice FROM property_listings WHERE property_intent = 'Rent'

答案 3 :(得分:-1)

第一个选项:

SELECT 
     property_intent,  
     MAX(property_price) AS LargestPrice, 
     MIN(property_price) AS LowestPrice 
FROM 
      property_listings 
WHERE  
      property_intent IN ('Sale', 'Rent') 
GROUP BY
      property_intent

第二个选项:

SELECT 
     'Sale' AS property_intent, 
     MAX(property_price) AS LargestPrice, 
     MIN(property_price) AS LowestPrice 
FROM 
     property_listings 
WHERE 
     property_intent = 'Sale'
UNION
SELECT 
     'Rent' AS property_intent, 
     MAX(property_price) AS LargestPrice, 
     MIN(property_price) AS LowestPrice 
FROM 
     property_listings 
WHERE 
     property_intent = 'Rent'