繁体   English   中英

如何在MySQL的同一张表上使用join合并这两个查询?

[英]How can i combine these two queries using join on the same table in 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'

我会做这样的事情。

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

使用嵌套查询:

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

这肯定会起作用:

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'

第一种选择:

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'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM