简体   繁体   English

无法编写我想要的mysql查询

[英]Cannot write mysql query i want

I have a table (Counts) with many entries like this: 我有一个表(计数),其中包含许多这样的条目:

ID | userid | count | entrydate

where ID is an autoinc PK, userid refers to my Users table, count is a random integer, and entrydate is a unix timestamp. 其中ID是autoinc PK,userid是指我的Users表,count是随机整数,entrydate是unix时间戳。

I also have a table called Listmembers: 我还有一个名为Listmembers的表:

listid | userid

where both fields together are PK, and listid refers to some list information. 其中两个字段都为PK,而listid则引用一些列表信息。

I want to write a query that returns the most recently inputted count value for each user in a specific list. 我想编写一个查询,该查询返回特定列表中每个用户的最新输入计数值。

I tried variations with GROUP BY (only returns the first inputted data item per userid, not the most recent), with ORDER BY (but this returns all counts for the relevant users), with user selection inside my query (where userid IN (..)) and outside the query (join listmembers on ..). 我尝试使用GROUP BY(仅返回每个用户ID输入的数据项,而不返回最新输入的数据项),使用ORDER BY(但返回相关用户的所有计数)的变体,并在查询中进行用户选择(其中userid IN(。 。))和查询之外(在..上加入列表成员)。 No query resulted in what i want to achieve :-/ 没有查询导致我想要实现的目标:-/

select c.userid, c.count  from counts C
inner join (select userid, max(entrydate)  
            from Counts group by userid) g 
   on c.userid =g.userid and c.entrydate = g.entrydate
inner join Listmembers L on l.userid = c.userid
where l.listid = @desiredList 

(Note: I've never actually used mysql. That should be the T-Sql syntax, but it should be standard enough to work on an SQL) (注意:我从未真正使用过mysql。这应该是T-Sql语法,但是应该足够标准才能在SQL上工作)

使用max()可以做到这一点:

max(entryDate)
SELECT c.count FROM Counts as c, Listmembers as l
 WHERE l.userid = c.userid 
        AND l.listid = 'specific_value'
        AND c.entrydate = MAX(c.entrydate)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM