doujie3888 2012-02-24 02:38
浏览 155
已采纳

MYSQL SELECT DISTINCT,结果集中包含其他列

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; 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

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

  • 写回答

3条回答 默认 最新

  • dsa80833 2012-02-24 02:57
    关注

    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. But other than that it works.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 怎么改成循环输入删除(语言-c语言)
  • ¥15 安卓C读取/dev/fastpipe屏幕像素数据
  • ¥15 pyqt5tools安装失败
  • ¥15 mmdetection
  • ¥15 nginx代理报502的错误
  • ¥100 当AWR1843发送完设置的固定帧后,如何使其再发送第一次的帧
  • ¥15 图示五个参数的模型校正是用什么方法做出来的。如何建立其他模型
  • ¥100 描述一下元器件的基本功能,pcba板的基本原理
  • ¥15 STM32无法向设备写入固件
  • ¥15 使用ESP8266连接阿里云出现问题