1

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

4

3 に答える 3

3

To get the lowest price per distinct name, you don't want DISTINCT, but rather 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.

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
于 2012-02-24T02:44:00.373 に答える
1

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)
于 2012-02-24T02:43:47.240 に答える
1

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.

于 2012-02-24T02:57:03.860 に答える