-1

请帮我写一个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 的不同 ref。就像我想要一些这样的东西user id = 1

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

请帮助我编写 sql 查询,因为这对我来说很难达到这个结果,谢谢。

4

2 回答 2

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
于 2013-06-18T13:10:00.997 回答
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
于 2013-06-18T13:10:25.240 回答