テーブルの構造を教えていただければ助かりますので、具体的に説明させていただきます。
これに似た構造を持っていると思います:
Table item: (id, itemname)
1 item1
2 item2
3 item3
4 item4
5 item5
Table tag: (id, tagname)
1 cool
2 red
3 car
Table itemtag: (id, itemid, tagid)
1 1 2 (=item1, red)
2 2 1 (=item2, cool)
3 2 3 (=item2, car)
4 3 1 (=item3, cool)
5 3 2 (=item3, red)
6 3 3 (=item3, car)
7 4 3 (=item3, car)
8 5 3 (=item3, car)
一般的に、私のアプローチは、それぞれの個別のタグを数えることから始めることです。
-- make a list of how often a tag was used:
select tagid, count(*) as `tagscore` from itemtag group by tagid
これにより、アイテムに割り当てられた各タグの行とスコアが表示されます。
この例では、次のようになります。
tag tagscore
1 2 (cool, 2x)
2 2 (red, 2x)
3 4 (car, 4x)
set @ItemOfInterest=2;
select
itemname,
sum(tagscore) as `totaltagscore`,
GROUP_CONCAT(tags) as `tags`
from
itemtag
join item on itemtag.itemid=item.id
join
/* join the query from above (scores per tag) */
(select tagid, count(*) as `tagscore` from itemtag group by tagid ) as `TagScores`
on `TagScores`.tagid=itemtag.tagid
where
itemid<>@ItemOfInterest and
/* get the taglist of the current item */
tagid in (select distinct tagid from itemtag where [email protected])
group by
itemid
order by
2 desc
説明:クエリには2つのサブクエリがあります。1つは、対象のアイテムからリストタグを取得することです。これらのみを処理します。他のサブクエリは、タグごとのスコアのリストを生成します。
したがって、最終的に、データベース内の各アイテムにはタグスコアのリストがあります。これらのスコアはsum(tagscore)
で合計されます 、およびその番号は、結果を並べ替えるために使用されます(一番上のスコアが最も高い)。
使用可能なタグのリストを表示するために、GROUP_CONCATを使用しました。
クエリの結果は次のようになります(実際のデータはここに作成しました):
Item TagsScore Tags
item3 15 red,cool,car
item4 7 red,car
item5 7 red
item1 5 car
item6 5 car