MySQL一对多关系,具有共享值

时间:2016-04-15 20:33:14

标签: php mysql

我有一个包含3个表的MySQL DB。

轮廓, p_tags, 标签

DB:

profile
pid | name

ptags
ptid | pid | tagid

tags
tagid | tag

数据库看起来像这样

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

我需要创建一个显示配置文件中具有共享标签和总共享标签的名称的查询

Results
Name  | Name2 | Count
Randy - Jeff - 1
Randy - Mike - 2
Jeff - Randy - 1
Jeff - Mike - 2 
Mike - Randy - 2
Mike - Jeff - 2

等等。

如果我正确解释的话,我不知道。

我读了

https://www.simple-talk.com/sql/t-sql-programming/divided-we-stand-the-sql-of-relational-division/

来自另一个类似于此帖子的帖子,但是我无法理解它:)。

SQLFiddle:http://sqlfiddle.com/#!9/42bde6

1 个答案:

答案 0 :(得分:2)

在查询中使用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

如果你只需要一行用于名字对,那么试试这个:

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;