基于最高列值的不同用户标识的SQL查询

时间:2013-06-18 13:06:59

标签: mysql sql mysql-python

请帮我写一个Django查询和MySql查询,我有一个像这样的表molesdetails:

+---+  +--------+  +----------+  +----------+
|id |  |user_id |  |   ref    |  |   set    |
+---+  +--------+  +----------+  +----------+
|1  |  |  1     |  |    1     |  |    1     |
|2  |  |  1     |  |    1     |  |    2     |
|3  |  |  1     |  |    2     |  |    3     |
|4  |  |  2     |  |    1     |  |    1     |
|5  |  |  2     |  |    1     |  |    2     |
|6  |  |  2     |  |    2     |  |    3     |
|7  |  |  1     |  |    2     |  |    4     |
+---+  +--------+  +----------+  +----------+

我希望我应该从设置最大的查询中获取特定用户ID的不同参考。就像我想要user id = 1这样的东西:

+---+  +--------+  +----------+  +----------+
|id |  |user_id |  |   ref    |  |   set    |
+---+  +--------+  +----------+  +----------+
|2  |  |  1     |  |    1     |  |    2     |
|7  |  |  1     |  |    2     |  |    4     |
+---+  +--------+  +----------+  +----------+

请帮我写一下sql查询,因为这对我来说很难实现这个结果,谢谢。

2 个答案:

答案 0 :(得分:1)

select t1.* 
from your_table t1
inner join
(
  select ref, max(set) as mset
  from your_table
  where user_id = 1
  group by ref
) t2 on t2.mset = t1.set and t2.ref = t1.ref

答案 1 :(得分:0)

您可以通过基本聚合完成大部分工作:

select user_id, ref, max(set) as set
from t
group by user_id, ref

问题是:如何获得id?这是一种可以在MySQL中使用的方法,不需要额外的连接:

select substring_index(group_concat(id order by set desc), ',', 1) as id,
       user_id, ref, max(set) as set
from t
group by user_id, ref