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

我有2个表,分别称为“父母”和“孩子”。


父母

parent_id |名称|


孩子

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个单独的列,而不是合并的单个列。

感谢您的帮助。


编辑


添加示例:

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

hexar 回答:mysql查询中两个不相关表的同一列中的唯一值

不需要加入,只需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         |
本文链接:https://www.f2er.com/2857651.html

大家都在问