我是一名新手sql程序员,所以我需要一些帮助来尝试获取查询。
我需要每周从桌子上播放独特的歌曲。
在某个星期说,已经播放了8首不同的歌曲,但是这8首歌曲每首都播放了很多次,我只想要出现8首歌曲。
我需要通过连接2个表格,一个STATS表和一个PLAYLIST表
来完成SELECT playlist.p_title AS title, stats.s_week AS week, playlist.p_artist AS artist, p_id
FROM stats, playlist
WHERE stats.s_pid = playlist.p_id
AND s_uid =31
ORDER BY s_week DESC
LIMIT 0 , 30
这是我的原始查询,它为我提供了所有周内播放的所有歌曲,即使它们已经在每周播放了很多次,这也是我不想要的。
任何人都能帮助我每周分清歌曲吗?
提前致谢 - Rasmus
答案 0 :(得分:1)
只需使用DISTINCT子句:
SELECT DISTINCT
playlist.p_title AS title,
stats.s_week AS week,
playlist.p_artist AS artist, p_id
FROM stats inner join playlist on stats.s_pid = playlist.p_pid
WHERE s_uid =31
ORDER BY s_week DESC
LIMIT 0 , 30
另外,最好使用table1 inner join table2 on table1.id = table2.id
而不是使用WHERE子句将两个表连接在一起。
答案 1 :(得分:1)
如果您想这样做for each week
,建议您查看GROUP BY
...
另外,我建议寻找有关使用JOIN
语法的教程(自1992年以来一直存在并且通常被认为是使用的标准。在各种RDBMS中经常不推荐使用,
。)
SELECT
stats.s_week AS week,
stats.p_id AS pid,
playlist.p_title AS title,
playlist.p_artist AS artist,
COUNT(*) AS plays /* This shows how many times a track was played */
FROM
stats
INNER JOIN
playlist
ON stats.s_pid = playlist.p_id
WHERE
s_uid =31
GROUP BY
stats.s_week,
stats.p_id,
playlist.p_title,
playlist.p_artist
ORDER BY
stats.s_week DESC
LIMIT
0 , 30
如果你没有在某些字段中包含表名,我也会将它们添加回来。
明确关于该领域的来源总是更好。对于GROUP BY
和其他用途,它通常是必需的。
答案 2 :(得分:0)
SELECT playlist.p_title AS title, stats.s_week AS week, playlist.p_artist AS artist, p_id
FROM stats, playlist
WHERE stats.s_pid = playlist.p_id
AND s_uid =31
group by playlist.p_title, stats.s_week,playlist.p_artist
ORDER BY s_week DESC
LIMIT 0 , 30