0

我是一个新手 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 

这是我的原始查询,它为我提供了所有周内播放的所有歌曲,即使它们每周播放了很多次,这是我不想要的。

谁能帮我区分每周的歌曲?

提前致谢 - 拉斯穆斯

4

3 回答 3

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

此外,最好使用 atable1 inner join table2 on table1.id = table2.id而不是使用 WHERE 子句将两个表连接在一起。

于 2012-11-19T10:57:02.113 回答
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和其他用途,它通常是必需的。

于 2012-11-19T10:59:53.427 回答
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 
于 2012-11-19T10:56:53.603 回答