简体   繁体   中英

How to merge two tables

Given this relation of two tables

table1: (name, height, age)

table2: (cname, weight)

I want to combine name and cname so they are one with no duplicates. Like for example, let's say the name column for table1 had

name
bob
mary
alice
steve

while the cname column for table2 had

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 .

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.

UNION removes duplicate records (where all columns in the results are the same), UNION ALL does not.

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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