简体   繁体   中英

Selecting Similar columns from multiple tables

My table structure is as follows:

Computer:
    id serial,
    sbeadminlogin text,
    sbeadminfirstname text,
    sbeadminlastname text

Server:
    id serial,
    sbeadminlogin text,
    sapadminfirstname text,
    sapadminlastname text

There is no relation between those tables however they have column sbeadminlogin which is named same in both. It is possible that the person who is administrator in Server table is also administrator of other device which is stored iin computer tables.

I would like to create list of all administrators(only unique rows) from those tables in one query. In order to do so I used:

(select distinct sbeadminlogin from computer)
union
(select distinct sbeadminlogin from server)

which works great until I wanted to add name and last name to be visible in the result like :

(select distinct sbeadminlogin, sbeadminfirstname || ' ' || sbeadminlastname from computer)
union
(select distinct sbeadminlogin, saeadminfirstname || ' ' || saeadminlastname from server)

I got the error saying that column saeadminfirstname does not exist.

Could anyone give me a hint how to prepare statement so I get unique logins, first and lastnames from both tables?

I believe that if you place the correct column names (with alias or not) it will work:

(select sbeadminlogin, sbeadminfirstname || ' ' || sbeadminlastname as adminname from computer)
union
(select sbeadminlogin, sapadminfirstname || ' ' || sapadminlastname as adminname from server)

Example: SQLFiddle

I think you should use +' '+ to concatenate two columns and not ||.

ex.

(select distinct name+' '+city+' '+lastname from temp1) union (select distinct name+' '+city+' '+lastname from temp2)

Try this query and check it :

(select distinct sbeadminlogin, sbeadminfirstname || ' ' || sbeadminlastname 
from computer)
union
(select distinct sbeadminlogin, sapadminfirstname || ' ' || sapadminlastname 
from server)

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