以下是你需要查詢:
SELECT DISTINCT B.* FROM
(SELECT ID,`Signal`,MIN(CONCAT(Station,'-',Owner)) MaxStationOwner
FROM (SELECT DISTINCT t.* FROM
(SELECT ID,MAX(`Signal`) `Signal` FROM t GROUP BY ID) AAA
LEFT JOIN t USING (ID,`Signal`)) AA
GROUP BY ID,`Signal`) A
INNER JOIN t B
ON A.MaxStationOwner=CONCAT(B.Station,'-',B.Owner)
AND A.ID=B.ID AND A.`Signal`=B.`Signal`;
這裏是您的樣本數據:
drop database if exists preeti;
create database preeti;
use preeti
create table t
(ID int not null,
`Signal` int not null,
Station varchar(10),
Owner varchar(10));
insert into t values
(111, -120 , 'Home' , 'M1'),
(111, -120 , 'Home' , 'M1'),
(111, -120 , 'Home' , 'M2'),
(111, -120 , 'Car' , 'M1'),
(111, -120 , 'Car' , 'M2'),
(111, -120 , 'Work' , 'M1'),
(111, -120 , 'Dept' , 'M3'),
(111, -130 , 'Car' , 'M1'),
(111, -135 , 'Work' , 'M2'),
(222, -98 , 'Home' , 'M2'),
(222, -95 , 'Work' , 'M1'),
(222, -103 , 'Work' , 'M2');
這裏被裝載示例數據:
mysql> drop database if exists preeti;
Query OK, 1 row affected (0.03 sec)
mysql> create database preeti;
Query OK, 1 row affected (0.00 sec)
mysql> use preeti
Database changed
mysql> create table t
-> (ID int not null,
-> `Signal` int not null,
-> Station varchar(10),
-> Owner varchar(10));
Query OK, 0 rows affected (0.06 sec)
mysql> insert into t values
-> (111, -120 , 'Home' , 'M1'),
-> (111, -120 , 'Home' , 'M1'),
-> (111, -120 , 'Home' , 'M2'),
-> (111, -120 , 'Car' , 'M1'),
-> (111, -120 , 'Car' , 'M2'),
-> (111, -120 , 'Work' , 'M1'),
-> (111, -120 , 'Dept' , 'M3'),
-> (111, -130 , 'Car' , 'M1'),
-> (111, -135 , 'Work' , 'M2'),
-> (222, -98 , 'Home' , 'M2'),
-> (222, -95 , 'Work' , 'M1'),
-> (222, -103 , 'Work' , 'M2');
Query OK, 12 rows affected (0.06 sec)
Records: 12 Duplicates: 0 Warnings: 0
mysql>
這裏是輸出:
mysql> SELECT DISTINCT B.* FROM
-> (SELECT ID,`Signal`,MIN(CONCAT(Station,'-',Owner)) MaxStationOwner
-> FROM (SELECT DISTINCT t.* FROM
-> (SELECT ID,MAX(`Signal`) `Signal` FROM t GROUP BY ID) AAA
-> LEFT JOIN t USING (ID,`Signal`)) AA
-> GROUP BY ID,`Signal`) A
-> INNER JOIN t B
-> ON A.MaxStationOwner=CONCAT(B.Station,'-',B.Owner)
-> AND A.ID=B.ID AND A.`Signal`=B.`Signal`;
+-----+--------+---------+-------+
| ID | Signal | Station | Owner |
+-----+--------+---------+-------+
| 111 | -120 | Car | M1 |
| 222 | -95 | Work | M1 |
+-----+--------+---------+-------+
2 rows in set (0.02 sec)
mysql>
試試看!
CAVEAT
請確保您有在表t這個索引:
ALTER TABLE t ADD INDEX ID_Signal_Index (ID,`Signal`);
你有沒有在此表中,使行唯一的任何其他列?主鍵可能? – piotrm 2012-01-10 21:33:39
嘗試在'SELECT'後面緊跟着'DISTINCT' – 2012-01-10 23:00:50
在Signal的後面加上了引號,因爲Signal是主要用於存儲過程的保留字。 – RolandoMySQLDBA 2012-01-10 23:11:53