根据一些建议,我将表分为三部分,以使用多对多查询,所以现在有了:
桌布动漫:
+----------------+-------------+
| id | title |
+----------------+-------------+
| 1 | Anime A |
| 2 | Anime B |
| 3 | Anime C |
+----------------+-------------+
流派:
+----------------+-------------+
| id | genre |
+----------------+-------------+
| 1 | Action |
| 2 | Romance |
| 3 | Ninja |
+----------------+-------------+
然后是第三张中间动漫和流派的表格:
+----------------+-------------+
| anime_id | genre_id |
+----------------+-------------+
| 1 | 1 |
| 1 | 3 |
| 2 | 2 |
| 2 | 3 |
| 3 | 2 |
+----------------+-------------+
给出一个动漫ID,就可以像这样获得它的体裁:
SELECT an.id, an.title, GROUP_CONCAT(g.genre) AS genres
FROM animes an
INNER JOIN intermediate_table ti ON ti.anime_id = an.id
INNER JOIN genres g ON g.id = ti.genre_id
WHERE an.id = 1
那么,如果我想根据常见流派的数量获得类似动漫的清单,该怎么办?就像我想知道所有与动漫1类似的动漫,并按常见流派的数量对它们进行排序。
答案 0 :(得分:1)
SELECT anime_id , COUNT(F.genre_id)
FROM anime_genre A
LEFT JOIN ( SELECT `genre_id`
FROM `anime_genre`
WHERE `anime_id` = 1 ) F
ON A.`genre_id` = F.`genre_id`
WHERE `anime_id` <> 1
GROUP BY anime_id
HAVING COUNT(F.genre_id) > 0
ORDER BY COUNT(F.genre_id) DESC
输出
我添加了另外一部动画来显示它们的相似程度
| anime_id | COUNT(F.genre_id) |
|----------|-------------------|
| 4 | 2 |
| 2 | 1 |