愚蠢的问题,我该如何加入2张桌子

table1
-------------
id  pagetitle
1   x
2   y
3   z
-------------


table2
------------
id   contentid      value
1     1             img.jpg
2     1             someval
3     1             someval2
4     2             x
5     3             y


RESULTS SHOULD BE ONE BIG TABLE
-----------------------------------------------------------------------------
id    pagetitle  id(idfrom table2...)  contentid   value1    value2   value3
1     x             1                     1        img.jpg   someval  someval2
2     y             4                     2        x
3     z             5                     3        y
-----------------------------------------------------------------------------


有兴趣获取每行的所有3个或更多值,无重复

我在查询(示例)中尝试​​了这部分代码,但是对于在table2中找到的每个值,我都会得到重复的行:

SELECT * FROM `table1` AS t1
           INNER JOIN `table2` AS t2
               ON t1.id = t2.contentid


谢谢

最佳答案

答案很困难,但是如果您可以将所有值都用逗号分隔的单列,那么下面的SQL语句应该为您服务:

SELECT t1.id, t1.pagetitle, t2.contentid, GROUP_CONCAT(value SEPARATOR ', ') as val
FROM table1 AS t1
    INNER JOIN table2 AS t2 ON t1.id = t2.contentid
GROUP BY t1.id, t1.pagetitle, t2.contentid


这将导致类似以下情况:

  id, pagetitle, contentid, val
  1 , x ,        1 ,        someval2, img, someval
  2 , y ,        2 ,        x
  3 , z ,        3 ,        y

10-06 05:42