[英]MySQL one to many relationship, with shared values
I have a MySQL DB with 3 tables. 我有一个包含3个表的MySQL DB。
profile, p_tags, tags 个人资料,p_tags,标签
DB: D B:
profile
pid | name
ptags
ptid | pid | tagid
tags
tagid | tag
The DB looks something like this DB看起来像这样
profile
pid | name
1 Randy
2 Jeff
3 Mike
ptags
ptid | pid | tagid
1 1 1
2 1 2
3 2 1
4 2 3
5 3 1
6 3 2
7 3 3
tags
tagid | tag
1 science
2 filosophy
3 hydrology
What I need is to create a query that displays The names in the profile that have shared tags and the total shared tags 我需要的是创建一个查询,显示配置文件中具有共享标签和总共享标签的名称
IE IE
Results
Name | Name2 | Count
Randy - Jeff - 1
Randy - Mike - 2
Jeff - Randy - 1
Jeff - Mike - 2
Mike - Randy - 2
Mike - Jeff - 2
And so on. 等等。
I dunno if I explained it correctly. 如果我正确解释的话,我不知道。
I read 我读
https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/ https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/
From a link from another post similar to this one, but just can't get my head around it :). 从另一个类似于这个的帖子的链接,但只是不能让我的头围绕它:)。
SQLFiddle: http://sqlfiddle.com/#!9/42bde6 SQLFiddle: http ://sqlfiddle.com/#!9/42bde6
in query use join: 在查询中使用join:
SELECT p1.name Name1, p2.name Name2, Count(tagid)
FROM ptags AS t1
INNER JOIN ptags AS t2 ON t2.tagid = t1.tagid and t2.ptid <> t1.ptid
INNER JOIN profile AS p1 ON p1.pid = t1.pid
INNER JOIN profile AS p2 ON p2.pid = t2.pid
GROUP BY p1.name, p2.name
and if you need only one row for pair of firstname then try this: 如果你只需要一行名字对,那么试试这个:
SELECT p1.firstname Name1, p2.firstname Name2, Count(t1.tagid)
FROM profile_hashtags AS t1
INNER JOIN profile_hashtags AS t2
ON t2.tagid = t1.tagid and t2.pHid > t1.pHid
INNER JOIN `profile` AS p1 ON p1.pid = t1.pid
INNER JOIN `profile` AS p2 ON p2.pid = t2.pid
GROUP BY p1.firstname, p2.firstname;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.