问题标题是感觉,我知道。但我的问题似乎难以解释。
我在phpmyadmin上有一个像这样的表
+-----+-----+----
| id |tag |item|
+=====+=====+===
| 1 | 1 | 132|
+-----+-----+---
| 2 | 2 | 132|
+-----+-----+---
| 3 | 2 | 134|
+-----+-----+---
| 4 | 1 | 135|
+-----+-----+---
我想查找相关项目的数量。
例如,item-132有1,2个标签值,item-134有2个标签值。 item-132和item-134具有相同的2个标记值。 SO item-132和item-134有一个相关标签。
我想让关系标签像这样......
如何在MySQL中设置获取关系标记计数的SQL查询。
答案 0 :(得分:1)
自我加入将帮助您入门:
select t1.item item1, t2.item item2, etc
from table t1 join table t2 on t1.item <> t2.item
and t1.tag = t2.tag
where whatever
答案 1 :(得分:1)
如果标签每个项目最多只存在一次,则可以使用自联接;
SELECT t2.item, COUNT(t2.id) cnt
FROM mytable t1
JOIN mytable t2
ON t1.tag=t2.tag AND t1.item<>t2.item
WHERE t1.item = 132
GROUP BY t2.item
答案 2 :(得分:0)
假设您希望关系计数在132到134之间,您可能需要考虑
SELECT COUNT(*) AS relcount
FROM tablename AS aa
INNER JOIN tablename AS bb ON aa.tag=bb.tag
WHERE aa.item=132
AND bb.item=134
答案 3 :(得分:0)
您可以执行以下操作:
SELECT COUNT(*) FROM tt t1
JOIN tt t2 ON t1.tag=t2.tag
WHERE t1.item = 132
AND t2.item = 134;
答案 4 :(得分:0)
sqlFiddle这将为您提供相关标签以及item1和item2(具有此相关标签的项目)
SELECT T1.tag,T1.item as item1,T2.item as item2
FROM yourTable T1
INNER JOIN yourTable T2
ON (T1.tag = T2.tag AND T2.item > T1.item)
然后如果你想要一个计数,你可以添加COUNT(T1.tag)和GROUP BY item1,item2像(sqlFiddle)
SELECT COUNT(T1.tag) as relatedCount,T1.item as item1,T2.item as item2
FROM yourTable T1
INNER JOIN yourTable T2
ON (T1.tag = T2.tag AND T2.item > T1.item)
GROUP BY item1,item2