This is a SQL question, I will try my best to explain.
I have a table like the following below
id name accounts
1 Jim 7001
1 Jim 7002
1 Jim 7003
2 Ryan 7001
3 Todd 7001
3 Todd 7003
2 Ryan 7002
4 Cam 7001
5 Fran 7001
2 Ryan 7003
1 Jim 7004
I am first trying to find all values with accounts column of '7001' to find the correct id's. After that I need to only pull the lines with those id's so I can see all the accounts for those specific ids.
example code I am using
select
s.id,
s.name,
s.account
from
students s
where
s.account in ('7001','7002','7003','7004')
I can do this with 2 queries one to find id's with '7001' account value and then run another query just for id's but would like to know if there is a way to write in order to have it all calculate in one shot.
Thanks in advance!
SELECT *
FROM tableName
WHERE ID IN
(
SELECT ID
FROM tableName
WHERE accounts = 7001
)
The JOIN
version ( recommended )
SELECT a.*
FROM students a
INNER JOIN students b
ON a.ID = b.ID
WHERE b.accounts = 7001
select t2.*
from tbl t1, tbl t2
where t1.accounts = '7001'
and t1.id = t2.id
This solution is optimized:
SELECT a.*
FROM tableName as a
INNER JOIN tableName as b
ON a.id = b.id
AND b.accounts = 7001
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.