mysql 查询中 2 个不相关表的同一列中的唯一值

Unique values in same column from 2 unrelated tables in mysql query

我有 2 个表,分别是 'parents' 和 'children'。


parents

parent_id |姓名 |


children

child_id | parent_id | child_name |

我正在寻找一个提供如下输出的查询:

parent_id(from parents) | name (unique names from both tables) | is_parent (1, if record is from parent table).

我尝试使用其中一个堆栈中的以下内容:

SELECT
   T1.name, T2.child_name
FROM
   parents T1
   LEFT OUTER JOIN
   children T2 ON T1.name = T2.child_name
UNION
SELECT
   T1.name, T2.child_name
FROM
   parents T1
   RIGHT OUTER JOIN
   children T2 ON T1.name = T2.child_name

但它给出了 2 个单独的列,而不是一个合并的单列。

感谢您的帮助。


编辑


添加示例:

不需要连接,只需 UNION ALL:

select parent_id, name, 1 is_parent from Parents
union all
select parent_id, child_name, 0 from Children

参见demo
结果:

| parent_id | name    | is_parent |
| --------- | ------- | --------- |
| 1         | Raja    | 1         |
| 2         | Sahil   | 1         |
| 3         | Ramesh  | 1         |
| 4         | Suresh  | 1         |
| 1         | Riya    | 0         |
| 1         | Rakesh  | 0         |
| 2         | Abhay   | 0         |
| 2         | Vishnu  | 0         |
| 3         | Rakesh  | 0         |
| 3         | Sunitha | 0         |