获取行并标记另一个表中存在的一些行

时间:2014-05-18 11:58:16

标签: mysql join

我有两张桌子。我想将users_logs.music_id=users_likes.music_idusers_logs.user_id=users_likes.user_id

加在一起

此表名为users_logs并且具有重复的行。

+----+----------+---------+
| id | music_id | user_id |
+----+----------+---------+
| id | 1        | 1       |
+----+----------+---------+
| id | 2        | 1       |
+----+----------+---------+
| id | 1        | 1       |
+----+----------+---------+
| id | 3        | 2       |
+----+----------+---------+
| id | 3        | 1       |
+----+----------+---------+

此表名为users_likes。

+----+----------+---------+
| id | music_id | user_id |
+----+----------+---------+
| id | 1        | 1       |
+----+----------+---------+
| id | 2        | 2       |
+----+----------+---------+
| id | 5        | 1       |
+----+----------+---------+

从{_ 1}}的user_logs获取最后3行的降序后,我想要输出以下内容:

user_id=1

如何在mysql中只进行1次查询?

1 个答案:

答案 0 :(得分:1)

如果我正确地遵循逻辑,那么这个查询应该做你想要的。它假定id列指定了从user_logs获取最后三行的顺序:

select ul.music_id, (uli.user_id is not null) as `like`
from (select ul.*
      from user_logs ul
      where user_id = 1
      order by id desc
      limit 3
     ) ul left outer join
     users_likes uli
     on ul.user_id = uli.user_id and ul.music_id = uli.music_id;