MySQL返回行,其中SAME TABLE中的x子行匹配第一行中的字段

时间:2016-08-08 03:31:07

标签: php mysql

有表'帖子':

-------------------------------------------------
|   id   |   name  |   url  | parentid |  type  |
-------------------------------------------------
|   1    | barname |  NULL  |   NULL   |  bar   |
-------------------------------------------------
|   2    |   NULL  |  beer  |    1     |  drink |
-------------------------------------------------
|   3    |   NULL  |  wine  |    1     |  drink |
-------------------------------------------------

需要获取行(父行),其中type =' bar',并加入行(子),其中type =' drink'和' parentid' =' id'。

期望的结果:

-----------------------------------------------------------------------------
|   id   |  name   |   url  | parentid |  type  | matchedurl1 | matchedurl2 |
-----------------------------------------------------------------------------
|   1    | barname |  NULL  |   NULL   |   bar  |    beer     |    wine     | 
-----------------------------------------------------------------------------

子行必须是可变数字。 (即结果需要有x个匹配的字段,具体取决于找到的子行数。)

谢谢。

3 个答案:

答案 0 :(得分:1)

这可能是表的数据透视问题,必须使用动态sql:

SET @sql = NULL;
SET @cnt = 0;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(CASE WHEN c.url = ''',
      c.url,
      ''' THEN c.url ELSE NULL END) AS matchedurl',
      @cnt := @cnt + 1
    )
  ) INTO @sql
FROM posts p
JOIN posts c
ON p.type = 'bar'
AND c.type = 'drink'
;

SET @sql = CONCAT('SELECT p.*, ', @sql,
                  ' FROM posts p
                  JOIN posts c
                  ON p.type = ''bar''
                  AND c.type = ''drink''
                  AND p.id = c.parentid
                  GROUP BY p.`id`');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Demo Here

答案 1 :(得分:0)

您可以尝试以下一个选项,用CSV列表匹配替换匹配列的可变数量:

SELECT t1.*, COALESCE(t2.matches, 'NA')
FROM posts p1
LEFT JOIN
(
    SELECT parentid, GROUP_CONCAT(url) AS matches
    FROM posts
    WHERE parentid IS NOT NULL
    GROUP BY parent_id
) p2
    ON p1.id = p2.parent_id
WHERE p1.parentid IS NULL

答案 2 :(得分:0)

我会用:

select p1.*, group_concat(p2.url) as matchedurl from posts p1
join posts p2 on p2.parentid=p1.id
group by parentid

结果将有一个matchedurl列,将您的结果连接起来,使其看起来像beer,wine

Live demo

然后在PHP中,您可以将结果解析为匹配数组:

$matchedUrls = explode(',', $row['matchedurl'];