如何selectMySQL中每个组的第一行?
在C#中会是这样的:
table .GroupBy(row => row.SomeColumn) .Select(group => group .OrderBy(row => row.AnotherColumn) .First() )
Linq-To-Sql将其转换为以下T-SQL代码:
SELECT [t3].[AnotherColumn], [t3].[SomeColumn] FROM ( SELECT [t0].[SomeColumn] FROM [Table] AS [t0] GROUP BY [t0].[SomeColumn] ) AS [t1] OUTER APPLY ( SELECT TOP (1) [t2].[AnotherColumn], [t2].[SomeColumn] FROM [Table] AS [t2] WHERE (([t1].[SomeColumn] IS NULL) AND ([t2].[SomeColumn] IS NULL)) OR (([t1].[SomeColumn] IS NOT NULL) AND ([t2].[SomeColumn] IS NOT NULL) AND ([t1].[SomeColumn] = [t2].[SomeColumn])) ORDER BY [t2].[AnotherColumn] ) AS [t3] ORDER BY [t3].[AnotherColumn]
但是它与MySQL不兼容。
我只根据你的post的标题来回答我的问题,因为我不知道C#,也不理解给定的查询。 但在MySQL中,我build议你尝试子查询。 首先获取一组感兴趣列的主键,然后从这些行中select数据:
SELECT somecolumn, anothercolumn FROM sometable WHERE id IN ( SELECT min(id) FROM sometable GROUP BY somecolumn );
当我写
SELECT AnotherColumn FROM Table GROUP BY SomeColumn ;
有用。 IIRC在其他RDBMS中这样的语句是不可能的,因为不属于分组键的列被引用而没有任何聚集。
这个“怪癖”的行为非常接近我想要的。 所以我用它来得到我想要的结果:
SELECT * FROM ( SELECT * FROM `table` ORDER BY AnotherColumn ) t1 GROUP BY SomeColumn ;
以下是另一种可以尝试的方法,即不需要该ID字段。
select some_column, min(another_column) from i_have_a_table group by some_column
我仍然同意lfagundes,你应该添加一些主键。
还要注意,通过这样做,你不能(容易地)得到的其他值是与生成的some_colum,another_column对相同的行! 你需要lfagundes的评价和一个PK来做到这一点!
你应该使用一些聚合函数来获得你想要的AnotherColumn的值。 也就是说,如果您想为SomeColumn的每个值(无论是数字还是按字典顺序排列)的AnotherColumn的最低值,您可以使用:
SELECT SomeColumn, MIN(AnotherColumn) FROM YourTable GROUP BY SomeColumn
一些希望有帮助的链接:
http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html
http://www.oreillynet.com/databases/blog/2007/05/debunking_group_by_myths.html
还有另一种方式来做到这一点
从视图中工作的组中select最大值
SELECT * FROM action a WHERE NOT EXISTS ( SELECT 1 FROM action a2 WHERE a2.user_id = a.user_id AND a2.action_date > a.action_date AND a2.action_type = a.action_type ) AND a.action_type = "CF"
这个怎么样:
SELECT SUBSTRING_INDEX( MIN(CONCAT(OrderColumn, '|', IFNULL(TargetColumn, '')) ), '|', -1) as TargetColumn FROM table GROUP BY GroupColumn
为什么不使用MySQL LIMIT关键字?
SELECT [t2].[AnotherColumn], [t2].[SomeColumn] FROM [Table] AS [t2] WHERE (([t1].[SomeColumn] IS NULL) AND ([t2].[SomeColumn] IS NULL)) OR (([t1].[SomeColumn] IS NOT NULL) AND ([t2].[SomeColumn] IS NOT NULL) AND ([t1].[SomeColumn] = [t2].[SomeColumn])) ORDER BY [t2].[AnotherColumn] LIMIT 1