我有一张这样的表:
-----------------------------
id | uid | year | other | many | fields
-----------------------------
1 | 1 | 2010 | blabla ...
2 | 2 | 1999 | blablabla ...
3 | 3 | 2011 | bla ...
4 | 1 | 2006 | blablablabla ...
...
-----------------------------
我想要的是选择
所有记录中的所有字段具有不同的uid
并且仅返回最后一条记录(即具有最高id
)
结果按年份排序
返回记录的示例,如:
-----------------------------
id | uid | year | other | many | fields
-----------------------------
2 | 2 | 1999 | blablabla ...
4 | 1 | 2006 | blablablabla ...
3 | 3 | 2011 | bla ...
-----------------------------
看起来与问题How to use DISTINCT and ORDER BY in same SELECT statement?类似,但我无法让它发挥作用。
我尝试SELECT * FROM table GROUP BY uid ORDER BY MAX(id) DESC, MAX(year)
,但似乎既没有排序id
也没有排序year
。
更新
感谢所有解决方案,这是一个新问题:我实际上在Discuz中开发插件,并且出于安全原因它不允许子查询,有没有办法只使用一个选择?或者在Discuz插件开发中的任何解决方法?再次感谢。
答案 0 :(得分:2)
据我所知,我可以给你两种方法,
(1)特定于Mysql
SELECT * FROM (SELECT * FROM `table_name` ORDER BY `id` DESC) tbl
GROUP BY `uid` ORDER BY `year`
注意:在Mysql中,我们不必为每个列应用GROUP BY
以获取其非聚合值,而只返回第一行。
(2)对于任何RDBMS
SELECT * FROM table_name
WHERE id IN (
SELECT Max(id) FROM table_name
GROUP BY uid
)
ORDER BY year
OR
SELECT tbl1.id, tbl1.uid, tbl1.year, tbl1.other
FROM table_name tbl1
INNER JOIN (
SELECT Max(id) id FROM table_name
GROUP BY uid
) tbl2
ON tbl1.id = tbl2.id
ORDER BY tbl1.year
以上所有陈述将产生与以下相同的结果:
----------------------------
| id | uid | year | other |
-----+-----+------+------------
| 2 | 2 | 1999 | blablabla ...
| 4 | 1 | 2006 | blablablabla ...
| 3 | 3 | 2011 | bla ...
-----------------------------
答案 1 :(得分:2)
你可以尝试这个
select distinct * from test where id IN (select MAx(id) id from test GROUP BY uid) order by year
test =>表名; 它会发出put作为
答案 2 :(得分:1)
以下查询可能会完成工作。
SELECT
your_table.id,
your_table.uid,
your_table.year,
your_table.other
FROM your_table
INNER JOIN
(
SELECT
uid,
MAx(id) max_id
FROM your_table
GROUP BY uid
) t
ON your_table.id = t.max_id AND your_table.uid = t.uid
ORDER BY your_table.id, your_table.year;
上述查询将在同一uid
下返回与最大ID 对应的记录,并按id
和year
的升序对记录进行排序。
SQL FIDDLE无效
测试数据:
DROP TABLE IF EXISTS `your_table`;
CREATE TABLE `your_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`uid` int(50) NOT NULL,
`year` int(11) NOT NULL,
`other` varchar(100) CHARACTER SET utf8 NOT NULL,
PRIMARY KEY (`id`)
);
INSERT INTO `your_table` VALUES ('1', '1', '2010', 'blabla ...');
INSERT INTO `your_table` VALUES ('2', '2', '1999', 'blablabla...');
INSERT INTO `your_table` VALUES ('3', '3', '2011', 'bla ...');
INSERT INTO `your_table` VALUES ('4', '1', '2006', 'blablablabla....');
<强>输出:强>
对这些测试数据运行上述查询,您将获得以下输出。
id uid year other
2 2 1999 blablabla...
3 3 2011 bla ...
4 1 2006 blablablabla....