0

Question title is senseles ,I know it. But my problem seems to diffucult to explain.

I have a one table on phpmyadmin like this

+-----+-----+----
| id |tag |item|
+=====+=====+===
| 1 |  1  | 132|
+-----+-----+---
| 2 |  2  | 132|
+-----+-----+---
| 3 |  2  | 134|
+-----+-----+---  
| 4 |  1  | 135|
+-----+-----+---

I want to find count of RELATED items.

For instance item-132 has 1,2 tag values and item-134 has 2 tag values. item-132 and item-134 has same 2 tag value. SO item-132 and item-134 has one related tag.

I want to get relation tags count like this ...

How can I set SQL query that get relation tag count in MySQL.

2
  • 2
    Can you give an example of the desired output? I found the question a bit hard to follow. Commented Dec 25, 2013 at 19:07
  • The item repeating is a typo? Commented Dec 25, 2013 at 19:07

5 Answers 5

1

A self join will get you started:

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
Sign up to request clarification or add additional context in comments.

Comments

1

Provided that the tags only exist at most once per item, you can use a self join;

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

An SQLfiddle to test with.

Comments

0

Assuming you want the relation count between 132 and 134, you might want to consider

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

1 Comment

Thank you Eugen its very usefull.
0

You can do as below:

SELECT COUNT(*) FROM tt t1 
JOIN tt t2 ON t1.tag=t2.tag 
WHERE t1.item = 132 
AND t2.item = 134;

Comments

0

sqlFiddle This will give you the related tag and the item1 and item2 (items that have this related tag)

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)

then if you want a count, you can add the COUNT(T1.tag) and GROUP BY item1,item2 like (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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.