简体   繁体   中英

SQL inner join on two tables

I have two tables, managers and users .

managers :

manager_user_id  user_user_id
---------------  ------------
1000011          1000031
1000011          1000032
1000011          1000033

etc.

users :

user_id  name
-------  ----
1000011  John
1000031  Jack
1000032  Mike
1000033  Paul

What I want to do is pull out a list of users' names and their user id's for a specific manager. So something like…

Users for John are:

1000031  Jack
1000032  Mike
1000033  Paul

I tried the following SQL, but it's wrong:

SELECT users.name, 
       users.user_id 
FROM   users 
       INNER JOIN managers 
           on users.user_id = managers.user_user_id 
WHERE  managers.manager_user_id='1000011'

I don't think there is error in your query.But you can try your query without quote as

SELECT users.name, 
       users.user_id 
FROM   users 
       INNER JOIN managers 
           on users.user_id = managers.user_user_id 
WHERE  managers.manager_user_id=1000011

Please try the following:

SELECT U.USER_ID, U.NAME
FROM USER U JOIN MANAGER M ON U.USER_ID = M.USER_USER_ID
JOIN USER U1 ON U1.USER_ID = M.MANAGER_USER_ID
WHERE M.MANAGER_USER_ID = ? OR U1.NAME = ?

Your query seems to be right,maybe your USER_ID is integer and you are comparing it with character string thats why its not working

another solution:

you can do it by using subquery also

SELECT U.USER_ID, U.NAME
FROM   USERS U
WHERE U.USER_ID IN (SELECT USER_USER_ID 
                    FROM MANAGER 
                    WHERE MANAGER_USER_ID IN (SELECT USER_ID FROM USERS WHERE NAME='John'))

Your query seems to be OK.
You can check the following SQL Fiddle .

select u.name, u.user_id, m.manager_user_id
from users u
left join managers m on m.user_user_id = u.user_id
;

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