简体   繁体   English

如何合并两个表

[英]How to merge two tables

Given this relation of two tables 给定两个表的这种关系

table1: (name, height, age) table1 :(名称,身高,年龄)

table2: (cname, weight) table2 :(名称,权重)

I want to combine name and cname so they are one with no duplicates. 我想将名称和cname结合在一起,所以它们是一个没有重复的名称。 Like for example, let's say the name column for table1 had 例如,假设table1的名称列具有

name
bob
mary
alice
steve

while the cname column for table2 had 而table2的cname列有

cname
bob
liam
abi
mark

I want to make a new name table like this: 我想创建一个新的名称表,如下所示:

name
bob
mary
alice
steve
liam
abi
mark

My attempt: 我的尝试:

SELECT
    name
FROM table1
    JOIN table2
        ON (table1.name = table2.cname)

I'm looking for a better join that'll make this work? 我正在寻找一个更好的联接,它将使这项工作吗? Anyway? 无论如何?

What you need is UNION . 您需要的是UNION

SELECT name from Table1
UNION
SELECT cname from Table2

This will combine the distinct result from two select queries. 这将合并来自两个选择查询的不同结果。

Here's a Demo . 这是一个演示

You can use both UNION and UNION ALL as per your requirement. 您可以根据需要使用UNIONUNION ALL

UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not. UNION删除重复的记录(结果中的所有列都相同),而UNION ALL不会。

Like: 喜欢:

#if you need distinct records.

SELECT name from Table1
UNION
SELECT cname from Table2;

#if you need all records.

SELECT name from Table1
UNION ALL
SELECT cname from Table2;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM