我的表格(产品)如下所示:
id name value
1 oil 100
2 oil 140
3 glue 120
4 glue 110
我需要选择最后插入的油并最后插入 glue ,因此结果应为:
2 oil 140
4 glue 110
我尝试了什么:
SELECT * FROM `products` GROUP BY `name` ORDER BY `value` DESC LIMIT 2
但此查询显示
1 oil 100
3 glue 120
答案 0 :(得分:2)
您需要获取每种类型的最后一行(最高ID),然后检索这些ID的数据。这假设您的ID编号随每次新插入而增加,因此较高的id值假定稍后插入。
SELECT d.id, d.name, d.value
FROM products d
JOIN (
SELECT MAX(id) id, name
FROM products
GROUP BY name
) m ON (d.id = m.id)
答案 1 :(得分:1)
试试这个: -
SELECT * FROM `products` GROUP BY `name` ORDER BY id DESC LIMIT 2
答案 2 :(得分:1)
此查询应该可以解决问题:
SELECT a.*
FROM products a
INNER JOIN (SELECT MAX(id) AS id
FROM products
GROUP BY name
) b
ON a.id = b.id;
答案 3 :(得分:1)
您需要在桌面上进行自我加入:
SELECT p1.id, p1.name, p1.value
FROM products p1
inner join
(
select name, max(id) mxid
from products
group by id
) p2
on p1.name = p2.name
and p1.id = p2.mxid
内部子查询获取记录的max()
id,然后将其加入表中以返回所需的记录。