select table_name.* from table_name,(select max(price) as price,pid from table_name group by pid) as table_name_temp where table_name_temp.price=table_name.price and table_name_temp.pid=table_name.pid;
--SQL code
create table lk1 (
uid int,
pid int,
price int,
`time` date
)engine=myisam;
insert into lk1 values
(1, 1, 100, '2007-07-01'),
(1, 2, 150, '2007-07-02 '),
(2, 1, 110, '2007-07-03 '),
(3, 1, 120, '2007-07-04 '),
(4, 2, 180, '2007-07-04 '),
(3, 2, 170, '2007-07-04 '),
(6, 3, 130, '2007-07-04 ');
select * from lk1 where price in (select max(price) from lk1 group by pid) group by pid;
--結果1:
query result(3 records)
uid pid price time
3 1 120 2007-07-04
4 2 180 2007-07-04
6 3 130 2007-07-04
truncate table lk1;
insert into lk1 values
(1, 1, 200, '2007-07-01'),
(1, 2, 200, '2007-07-02 '),
(2, 1, 110, '2007-07-03 '),
(3, 1, 120, '2007-07-04 '),
(4, 2, 180, '2007-07-04 '),
(3, 2, 170, '2007-07-04 '),
(6, 3, 130, '2007-07-04 ');
select * from lk1 where price in (select max(price) from lk1 group by pid) group by pid;
--結果2:
query result(3 records)
uid pid price time
1 1 200 2007-07-01
1 2 200 2007-07-02
6 3 130 2007-07-04
根據MySQL的手冊上面找到一個查詢,修改了一下發現也可以實現,但是並不理解什麼意思,不知道有沒有人給解釋一下
SQL codeSELECT *
FROM lk1 l1
WHERE price = (
SELECT MAX( l2.price )
FROM lk1 l2
WHERE l1.`pid` = l2.`pid` ) ;
--SQL code
create table lk1 (
uid int,
pid int,
price int,
`time` date
)engine=myisam;
insert into lk1 values
(1, 1, 100, '2007-07-01'),
(1, 2, 150, '2007-07-02 '),
(2, 1, 110, '2007-07-03 '),
(3, 1, 120, '2007-07-04 '),
(4, 2, 180, '2007-07-04 '),
(3, 2, 170, '2007-07-04 '),
(6, 3, 130, '2007-07-04 ');
select * from (select * from lk1 order by price desc) T group by pid;
--結果1:
query result(3 records)
uid pid price time
3 1 120 2007-07-04
4 2 180 2007-07-04
6 3 130 2007-07-04
truncate table lk1;
insert into lk1 values
(1, 1, 200, '2007-07-01'),
(1, 2, 200, '2007-07-02 '),
(2, 1, 110, '2007-07-03 '),
(3, 1, 120, '2007-07-04 '),
(4, 2, 180, '2007-07-04 '),
(3, 2, 170, '2007-07-04 '),
(6, 3, 130, '2007-07-04 ');
select * from (select * from lk1 order by price desc) T group by pid;
--結果2:
query result(3 records)
uid pid price time
1 1 200 2007-07-01
1 2 200 2007-07-02
6 3 130 2007-07-04
insert into lk1 values
(4, 3, 200, '2007-07-05 '),
(5, 3, 210, '2007-07-05' );
select * from (select * from lk1 order by price desc) T group by pid;
--結果3:
query result(3 records)
uid pid price time
1 1 200 2007-07-01
1 2 200 2007-07-02
5 3 210 2007-07-05