如何取相关postMySql?

How to take related post MySql?

我正在尝试根据标签post获取相关信息

例如我有table这样的

------------------------
post_id  |  term_id   |
-----------------------
   11    |     3      | 
   11    |     7      | 
   11    |     9      | 
   14    |     9      |
   14    |     1      |
   15    |     2      | 
   16    |     3      |
   16    |     4      | 
   16    |     8      | 
   16    |     2      | 
   18    |     3      | 
   18    |     4      | 
   18    |     5      |
   19    |     4      | 
   19    |     7      | 
...etc.,,
-----------------------

在上面 table post_id 11 有 3 term_id 3,7,9 所以现在我需要检查相同的 table 和 select other post 有相同的 term_id.. post_id 16 , 18 有 term_id 3 ,然后 post_id 19 有 7 term_id 但 term_id 9 不匹配所以我必须显示另一列相关 posts id 16,18,19 像这样

post id 14 有术语 id 9 和 1 但没有其他 post 有 9 和 1 所以这个 post 没有任何相关的 posts

------------------------------------------
post_id  |  term_id    |  related_post_id |
------------------------------------------
   11    |  3,7,9      |  16,18,19
   14    |  9,1        |  null
   15    |  2          |  16
   16    |  3,4,8,2    |  11,15,18,19
   18    |  3,4,5      |  11,16,19
   19    |  4,7        |  11,16,18
...etc.,,
------------------------

请有人帮忙解决这个任务。

好的..您可以使用此 group_concat 函数...但大小有 1024 字节的限制..这会起作用。否则..您正在查看 SP 中的复杂 SQL 来构建答案

select 
    tmp1.post_id, 
    myterm_id_list, 
    group_concat(distinct t2.post_id separator  ',') from

 (SELECT 
    distinct t1.post_id, 
    GROUP_CONCAT(distinct t1.term_id SEPARATOR ',') as myterm_id_list
  FROM  test.tablename t1 
  left join test.tablename t2  on
      t2.post_id= t1.post_id
  GROUP BY t1.post_id
 ) as tmp1

 left join test.tablename t2 on
    t2.term_id in (tmp1.myterm_id_list)
 group by 
    tmp1.post_id,
    myterm_id_list