MySQL从表中的用户列表中选择每个用户的最后一行

时间:2016-09-05 06:37:05

标签: mysql moodle

我试图从Moodle表中选择列表中每个用户的最后一行。 我的查询是

SELECT *
FROM mdl_logstore_standard_log
WHERE eventname='\\core\\event\\user_enrolment_created'
AND courseid=34
AND relateduserid IN(120,128)
GROUP BY relateduserid;`

我使用的表是:

MariaDB [**** _ *****]>描述mdl_logstore_standard_log;

+-------------------+--------------+------+-----+---------+----------------+
| Field             | Type         | Null | Key | Default | Extra          |
+-------------------+--------------+------+-----+---------+----------------+
| id                | bigint(10)   | NO   | PRI | NULL    | auto_increment |
| eventname         | varchar(255) | NO   |     |         |                |
| component         | varchar(100) | NO   |     |         |                |
| action            | varchar(100) | NO   |     |         |                |
| target            | varchar(100) | NO   |     |         |                |
| objecttable       | varchar(50)  | YES  |     | NULL    |                |
| objectid          | bigint(10)   | YES  |     | NULL    |                |
| crud              | varchar(1)   | NO   |     |         |                |
| edulevel          | tinyint(1)   | NO   |     | NULL    |                |
| contextid         | bigint(10)   | NO   | MUL | NULL    |                |
| contextlevel      | bigint(10)   | NO   |     | NULL    |                |
| contextinstanceid | bigint(10)   | NO   |     | NULL    |                |
| userid            | bigint(10)   | NO   | MUL | NULL    |                |
| courseid          | bigint(10)   | YES  | MUL | NULL    |                |
| relateduserid     | bigint(10)   | YES  |     | NULL    |                |
| anonymous         | tinyint(1)   | NO   |     | 0       |                |
| other             | longtext     | YES  |     | NULL    |                |
| timecreated       | bigint(10)   | NO   | MUL | NULL    |                |
| origin            | varchar(10)  | YES  |     | NULL    |                |
| ip                | varchar(45)  | YES  |     | NULL    |                |
| realuserid        | bigint(10)   | YES  |     | NULL    |                |
+-------------------+--------------+------+-----+---------+----------------+

我对这个查询的问题是它给了我列表中每个用户ID的第一行,我想要最后一行。我尝试通过id desc订购,但没有任何改变。

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

SELECT 
L.*
FROM mdl_logstore_standard_log L
INNER JOIN 
(

 SELECT 
  relateduserid,
  MAX(id) AS max_id
 FROM mdl_logstore_standard_log
 WHERE eventname='\\core\\event\\user_enrolment_created'
 AND courseid=34
 AND relateduserid IN(120,128)
 GROUP BY relateduserid
)AS t 
ON L.id = t.max_id

首先获取relateduserids的最大自动增量ID,然后在mdl_logstore_standard_logt表之间进行内部联接将返回您的预期结果。

答案 1 :(得分:0)

尝试这个,但我没有测试它

select * from mdl_logstore_standard_log where eventname='\\core\\event\\user_enrolment_created' and courseid=34 and relateduserid IN(120,128)  GROUP BY relateduserid ORDER BY id DESC LIMIT 1;