如何在MySQL的同一个表上使用join组合这两个查询?
使用嵌套查询:如何在MySQL的同一个表上使用join组合这两个查询?,mysql,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 LowestRentP
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 *
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
它改变了输出,但效果更好,因为不需要为最小和最大价格硬编码不同的结果字段名称。这更多地使用了SQL—结果包括property\u intent
,因此在处理结果时,您知道哪个是哪个,并且可以从那里进一步查找。当您想要添加其他属性\u intent
值时,只需将放置在其中,即可获得完整的报告
这肯定会奏效:
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;
第一种选择:
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
您能澄清一下您希望输出是什么样子吗?对于查询来说,表模式也不错。我想,在这一点上,你不再需要帮助进行查询了:PCREATE TABLEproperty\u listings
(property\u id
int(11)not NULL,property\u price
decimal(15,2)not NULL,property\u intent
varchar(10)not NULL)ENGINE=InnoDB DEFAULT CHARSET=latin1;在财产清单中插入价值(2,'45345346.00','Sale'),(4,'56236666.00','Sale'),(5,'9898999.00','Rent'),(6,'780000.00','Rent'),(8,'560000090.00','Sale'),(35,'123.00','Sale'),(40,'4536456.00','Sale'),等等,(41,'562369.00','租金',(43,'89000000.00','出售'),(62,'5892323.00','出售');非常好。sql fiddle更好!顺便说一句,看看我是如何做sql fiddle的。如果你有sql问题,并且你包括了一个fiddle,那么答案的质量会飙升。谢谢你的帮助。但是我真的必须保持我的输出,因为我将使用输出的数字(最高价、最低价、最高价和最低价)它确实回答了这个问题,我同意你的看法。除了明显的缺陷:-(
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'