简体   繁体   English

MYSQL SELECT DISTINCT在结果集中有其他列

[英]MYSQL SELECT DISTINCT with additional column in result set

Here's an example table: 这是一个示例表:

CREATE TABLE `deals_unsorted`.`temp_demo` (
`id` INT( 4 ) NOT NULL AUTO_INCREMENT ,
`price` INT( 5 ) NOT NULL ,
`name` VARCHAR( 50 ) NOT NULL ,
PRIMARY KEY ( `id` )
) ENGINE = MYISAM 

and some sample data 和一些样本数据

INSERT INTO `deals_unsorted`.`temp_demo` (
`id` ,
`price` ,
`name`
)
VALUES (
'1', '1300', 'suite'
), (
'2', '1200', 'suite'
), (
'3', '1100', 'standard'
), (
'4', '1000', 'standard'
), (
'5', '800', 'basic'
), (
'6', '900', 'basic'
), (
'7', '500', 'dorn room'
), (
'8', '500', 'dorm room'
), (
'9', '800', 'twin'
), (
'10', '750', 'twin'
)

But how in the world do I find all distinct rooms with the lowest price? 但是,如何在世界范围内找到价格最低的所有不同房间?

I've tried SELECT DISTINCT(name), MIN(price) FROM temp_demo; 我试过SELECT DISTINCT(name), MIN(price) FROM temp_demo; and many variations but the computer said no thanks with a: 和许多变化,但是计算机说不,谢谢:

1140 - Mixing of GROUP columns (MIN(),MAX(),COUNT(),...) with no GROUP columns is illegal if there is no GROUP BY clause 1140-如果没有GROUP BY子句,则将GROUP列(MIN(),MAX(),COUNT(),...)与GROUP列混合使用是非法的

If anyone can help me out with this simple table I'm sure it'll be a help to others too. 如果有人可以用这个简单的表格帮助我,我相信它也会对其他人有所帮助。 I've seen many examples with complicated tables and I just can't get my head around it. 我已经看到了许多带有复杂表格的示例,但我只是无法理解。

What I'm hoping for is the entire rows: 我希望的是整个行:

2, 1200, suite
4, 1000, stanbard
5, 800, basic
7 or 8, 500, dorm room
10, 750, twin

Because these have the lowest price for their distinct name 因为这些具有其独特名称的最低价格

To get the lowest price per distinct name, you don't want DISTINCT , but rather GROUP BY . 为了获得每个唯一名称的最低价格,您不需要DISTINCT ,而是需要GROUP BY The name/price pair returned by the inner GROUP BY query is then matched with the id value from the rest of the table with a JOIN . 然后,内部GROUP BY查询返回的名称/价格对通过JOIN与表其余部分的id值匹配。

SELECT id, nmin.name, nmin.price
FROM deals_unsorted JOIN (
  SELECT name, MIN(price) AS price FROM deals_unsorted GROUP BY name
) nmin ON deals_unsorted.name = nmin.name AND deals_unsorted.price = nmin.price

Since you also want to return the room number, you'll need a correlated subquery. 由于您还想返回房间号,因此需要一个相关的子查询。 Note that this will return two records for ties rather than joining the numbers with an or. 请注意,这将返回两个联系记录,而不是将数字与或连接在一起。

   select * from temp_demo t1 where price=(select min(price) 
from temp_demo t2 where t1.name=t2.name)

This does the job: 这可以做到:

SELECT id, name, MIN(price)FROM deals_unsorted GROUP BY name

Well, almost. 好吧,差不多。 It doesn't return 7 or 8, 500, dorm room . 它不会返回7或8,500,宿舍 But other than that it works. 但是除此之外,它还可以工作。

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

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