MYSQL SELECT DISTINCT 歌曲 ID、时间 按时间排序

发布于 2024-11-25 06:47:42 字数 334 浏览 0 评论 0原文

我的音乐网站主页上有一个当前正在收听的盒子,并且有一个这样的表:

id,userid,songid,time

现在每次用户播放歌曲时,歌曲的 id 都会插入到 Songid 字段中,同时也会插入时间。所以有时我有重复的songid(由不同用户插入)。

现在这是我的 sql 语句:

SELECT DISTINCT songid,time FROM songs ORDER BY time DESC LIMIT 10

它给了我最近听过的十首歌曲,但有时它也会返回重复的数据!我该如何解决这个问题?提前致谢

i have a currently listening box on the homepage of my music website, and i have a table like this:

id,userid,songid,time

now every time a user plays a song, the id of the song is inserted into the songid field and also the time. so sometimes i have duplicate songid (inserted by different users).

Now here is my sql statement:

SELECT DISTINCT songid,time FROM songs ORDER BY time DESC LIMIT 10

that gives me the last ten songs that were listened, however sometimes it returns duplicate data too! how can i fix this problem? Thanks in advance

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

颜漓半夏 2024-12-02 06:47:42

您需要聚合 songid

SELECT songid, MAX(time) AS most_recent_time
FROM songs
GROUP BY songid
ORDER BY most_recent_time DESC
LIMIT 10

You'll want to aggregate over songid:

SELECT songid, MAX(time) AS most_recent_time
FROM songs
GROUP BY songid
ORDER BY most_recent_time DESC
LIMIT 10
怪我闹别瞎闹 2024-12-02 06:47:42

如果时间是歌曲上次播放的日期时间,您可以根据上次播放时间对 gon 进行分组:

SELECT songid,MAX(time)
FROM songs
GROUP BY songid
ORDER BY time DESC
LIMIT 10

If the time is the datetime the song was last played, you can group the gons with the last time each was played:

SELECT songid,MAX(time)
FROM songs
GROUP BY songid
ORDER BY time DESC
LIMIT 10
泼猴你往哪里跑 2024-12-02 06:47:42
SELECT  *
FROM    songs s
WHERE   id =
        (
        SELECT  id
        FROM    songs si
        WHERE   si.songid = s.songid
        ORDER BY
                si.songid DESC, si.time DESC, si.id DESC
        LIMIT 1
        )
ORDER BY
        time DESC, id DESC
LIMIT 10

创建以下索引:

songs (songid, time, id)
songs (time, id)

以便快速运行。

GROUP BY Songid解决方案不同,这不需要对歌曲进行全表扫描或全索引松散扫描。

SELECT  *
FROM    songs s
WHERE   id =
        (
        SELECT  id
        FROM    songs si
        WHERE   si.songid = s.songid
        ORDER BY
                si.songid DESC, si.time DESC, si.id DESC
        LIMIT 1
        )
ORDER BY
        time DESC, id DESC
LIMIT 10

Create the following indexes:

songs (songid, time, id)
songs (time, id)

for this to work fast.

Unlike the GROUP BY songid solutions, this does not require a full table scan or a full index loose scan on songs.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文