MySQL 执行 LEFT JOIN 但包含父记录 ID 的查询?

MySQL query that performs LEFT JOIN but includes parent record's ID?

我有 table 个 articles,其中一些文章有子项(但只有 1 个级别的子项)。

我想要一个显示按父 ID 分组的文章的视图。这是我目前所拥有的。

select 
    `articles`.`id` AS `group_id`, `child`.`id` AS `article_id`,  `articles`.`created` AS `date`
from
    `articles`
    left join `articles` as `child` on (`articles`.`id` = `child`.`parent_id`)
where
    `child`.`id` is not null;

以上产生了这些结果。

trend_id,article_id,date
3374,3172,"2015-04-30 18:31:12"
3374,3211,"2015-04-30 18:31:12"
3374,3213,"2015-04-30 18:31:12"
3297,3217,"2015-04-30 18:31:10"
3170,3222,"2015-04-30 18:31:08"
3187,3226,"2015-04-30 18:31:09"
3187,3281,"2015-04-30 18:31:09"
3170,3284,"2015-04-30 18:31:08"
3170,3285,"2015-04-30 18:31:08"
3170,3320,"2015-04-30 18:31:08"
3187,3323,"2015-04-30 18:31:09"
3187,3333,"2015-04-30 18:31:09"
3187,3355,"2015-04-30 18:31:09"
3297,3393,"2015-04-30 18:31:10"

article_id 列不包含父 ID,而仅包含子 ID(对于这种联接而言是预期的)。

我需要的是这样的东西

trend_id,article_id,date
3374,3374,"2015-04-30 18:31:12"  <-- trend_id is repeated as article_id
3374,3172,"2015-04-30 18:31:12"
3374,3211,"2015-04-30 18:31:12"
3374,3213,"2015-04-30 18:31:12"
3297,3297,"2015-04-30 18:31:10"  <-- trend_id is repeated as article_id
3297,3217,"2015-04-30 18:31:10"
3170,3170,"2015-04-30 18:31:08"  <-- trend_id is repeated as article_id
3170,3222,"2015-04-30 18:31:08"

我一直在尝试修改查询以获得上述结果,但没有成功。我怀疑它需要 2 个连接,但我没有运气。

你可以用 UNION 解决这个问题:

select 
    `articles`.`id` AS `group_id`, `child`.`id` AS `article_id`,  `articles`.`created` AS `date`
from
    `articles`
    left join `articles` as `child` on (`articles`.`id` = `child`.`parent_id`)
where
    `child`.`id` is not null;
UNION 
select distinct
    `articles`.`id` AS `group_id`, `articles`.`id` AS `article_id`,  `articles`.`created` AS `date`
from
    `articles`

或者类似的东西

在这种情况下,一开始保持简单并将您想要的结果集分解成各个组成部分可能会有所帮助。
您已经有了 child 条目,现在您只需要 parent 行。

所以一种方法是简单地 UNION parent 行与您现有的查询:

SELECT 
    `articles`.`id` AS `group_id`, 
    `child`.`id` AS `article_id`,  
    `articles`.`created` AS `date`
FROM
    `articles`
    LEFT JOIN `articles` AS `child` ON (`articles`.`id` = `child`.`parent_id`)
WHERE
    `child`.`id` IS NOT NULL 

UNION ALL
SELECT 
    `articles`.`id` AS `group_id`, 
    `articles`.`id` AS `article_id`,  
    `articles`.`created` AS `date`
FROM
    `articles`
WHERE
    `articles`.`id` IN (SELECT DISTINCT `parent_id` FROM `articles`);