我的表格看起来像这样:
| id | user | data |
--------------------
| 1 | 11 | aaa1 |
| 2 | 11 | aaa2 |
| 3 | 11 | aaa3 |
| 4 | 22 | aaa4 |
| 5 | 33 | aaa5 |
| 6 | 33 | aaa6 |
| 7 | 44 | aaa7 |
我想选择包含所有数据的所有行,并且我希望每max id
添加user
的数据,如下所示:
| id | user | data | f_id | f_data |
------------------------------------
| 1 | 11 | aaa1 | 3 | aaa3 |
| 2 | 11 | aaa2 | 3 | aaa3 |
| 3 | 11 | aaa3 | 3 | aaa3 |
| 4 | 22 | aaa4 | 4 | aaa4 |
| 5 | 33 | aaa5 | 6 | aaa6 |
| 6 | 33 | aaa6 | 6 | aaa6 |
| 7 | 44 | aaa7 | 7 | aaa7 |
这是我的查询尝试:
SELECT t1.*, t2.id AS f_id, t2.data AS f_data
FROM table1 t1
LEFT JOIN table1 t2
ON t1.user=(SELECT MAX(t2.id)
FROM table1 t2
WHERE t2.user = t1.user )
更新 所有答案都是正确的,但是当我在80K +行的表上运行查询时,MySQL需要大量时间来执行查询。对于我的项目,我将添加ajax,以便用户可以点击它,php将执行每次点击一行的查询。
答案 0 :(得分:2)
<强> SQL Fiddle Demo 强>
SELECT t1.*,
t2.id AS f_id,
t2.data AS f_data
FROM table1 t1
JOIN table1 t2
ON t1.user = t2.user
AND t2.id = (SELECT MAX(t2.id)
FROM table1 t3
WHERE t3.user = t1.user)
答案 1 :(得分:0)
这样就可以了。
SELECT t1.*, t3.id AS f_id, concat(SUBSTRING(t1.data, 1, CHAR_LENGTH(t1.data)-1),t3.id) AS f_data
FROM table1 t1
INNER JOIN (select max(t2.id) as id, t2.user as userid from table1 t2 group by t2.user) t3
on t3.userid = t1.user
Sqlfiddle:http://sqlfiddle.com/#!9/a24413/7
答案 2 :(得分:0)
你可以使用你的逻辑来解决这个问题。只需要解决一些问题:
SELECT t1.*, t2max.id AS f_id, t2max.data AS f_data
FROM table1 t1 JOIN
table1 t2max
ON t1.user = t2max.user AND
t2max.id = (SELECT MAX(t2.id)
FROM table1 t2
WHERE t2.user = t1.user
);
变化是:
FROM
子句中为用户提供两个表之间的条件。id
而不是user
。