简体   繁体   中英

How I can do the SQL query using two tables

I have these two tables:

  1. Users - where we take County and City ID's by user ID
  2. Names_list - where located both City or County names

Users

id | county | city
---+--------+-----
1  | 123    | 456

Names_list

id  | name
----+-----
123 | ABC
456 | DEF

Query:

SELECT Users.id as id,  
  Users.county as county, 
  Users.city as city,  
  Names_list.name as name1 
  Names_list.name as name2 
FROM `Users` 
LEFT JOIN Names_list ON (Names_list.id = Users.city) 
LEFT JOIN Names_list ON (Names_list.id = Users.county) 
WHERE Users.id = '1'

This output needs to be returned:

id | county | name1 | city | name2
---+-------+--------+------+------
1  | 123    | ABC   | 456  | DEF

But, output is wrong, of course. Names_list.id are duplicated. Needs to be another solution to return in one line.

You just need aliases:

SELECT u.id as id, u.county as county, u.city as city,  
       nc.name as name1  nco.name as name2 
FROM `Users` u LEFT JOIN
     Names_list nc
     ON nc.id = u.city LEFT JOIN 
     Names_list nco
    ON nco.id = u.county
WHERE u.id = 1;  -- I'm guessing this is a number so am removing the single quotes.

You need to add different aliases to the two different. See live demo here and sql below. Note that it would be cleaner to have an entity type structure to tell apart city vs country IDs.

with Users(id,country,city)
as
(
select 1,123,456
), Names_list(id,name)
as
(
select 123,'ABC' union all
select 456,'DEF'
)
select    Users.*,
          city.name as city,
          country.name as country
from      Users
left join Names_list as city
          on city.id = Users.city
left join Names_list as country
          on country.id = Users.country
where     Users.id = 1

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