我是新来的,但我有一个小问题。
我有这个表(例如)
id | client| date
------------------------------
7 | v1 | 2015-05-20
6 | v1 | 2015-05-20
5 | v1 | 2015-05-01
4 | v1 | 2015-03-05
3 | v2 | 2015-02-02
2 | v3 | 2015-01-30
1 | v1 | 2015-01-01
我需要来自最后一个客户端的第一行,这种方式是客户端v1,但是当我选择最小日期时,结果是来自id = 7的v1,但我不需要该id。
我需要id 4,因为它是上一个客户端的第一个(较旧的)id。
我需要从该结果中查询。
我使用此查询:
$re=mysql_query('SELECT traffic.*, client.alias FROM traffic INNER JOIN service ON traffic.service_id = service.service_id INNER JOIN client ON service.client_id= client.client_id WHERE vehicle="'.$_GET['s'].'" AND client.alias = "'.$Days1.'" GROUP BY client.alias ORDER BY traffic.date ASC LIMIT 1');
我的表是:
mysql> select traffic_id, service_id, date, vehicle from traffic limit 5;
+-------------+-------------+---------------------+----------------+
| traffic_id | service_id | date | vehicle |
+-------------+-------------+---------------------+----------------+
| 1057967 | 1106746 | 2012-01-02 06:35:23 | 2816 |
| 1057968 | 1106747 | 2012-01-02 06:35:55 | 2817 |
| 1057969 | 1106748 | 2012-01-02 06:36:11 | 48789 |
| 1057970 | 1106749 | 2012-01-02 06:37:27 | 48888 |
| 1057971 | 1106750 | 2012-01-02 06:37:59 | 48887 |
+-------------+-------------+---------------------+----------------+
5 rows in set (0.00 sec)
mysql> select service_id, client_id from service limit 5;
+-------------+------------+
| service_id | client_id |
+-------------+------------+
| 1106746 | 1 |
| 1106747 | 2 |
| 1106748 | 2 |
| 1106749 | 3 |
| 1106750 | 4 |
+-------------+------------+
5 rows in set (0.02 sec)
mysql> select client_id, alias from client limit 5;
+------------+------------+
| client_id | alias |
+------------+------------+
| 1 | EXPRESS |
| 2 | CONWAY |
| 3 | ACC |
| 4 | GO |
| 5 | ACCEL |
+------------+------------+
5 rows in set (0.02 sec)
有什么建议吗?
答案 0 :(得分:1)
你可以尝试一下:
SELECT
cd1.id,
cd1.client,
cd1.`date`
FROM clientData AS cd1
INNER JOIN (
SELECT *
FROM clientData
ORDER BY id DESC
LIMIT 1
) AS cd2 ON cd1.client = cd2.client AND cd1.id != cd2.id
ORDER BY cd1.`date`
LIMIT 1;
这是sqlfiddle。
答案 1 :(得分:0)
所以,例如......
SELECT x.*
FROM my_table x
JOIN
( SELECT * FROM my_table ORDER BY id DESC LIMIT 1 ) y
ON y.client = x.client
AND y.id > x.id
ORDER
BY x.id DESC
LIMIT 1;