[英]sql - find value from a column to find all other values from another column
This is a SQL question, I will try my best to explain. 这是一个SQL问题,我将尽力解释。
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. 我首先尝试使用“ 7001”的“帐户”列查找所有值,以查找正确的ID。 After that I need to only pull the lines with those id's so I can see all the accounts for those specific ids.
之后,我只需要拉出带有这些ID的行,这样我就可以看到这些特定ID的所有帐户。
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. 我可以使用2个查询来执行此操作,一个查询找到具有“ 7001”帐户值的ID,然后运行另一个仅查询ID的查询,但想知道是否有一种写方法,以便一次计算所有的ID。
Thanks in advance! 提前致谢!
SELECT *
FROM tableName
WHERE ID IN
(
SELECT ID
FROM tableName
WHERE accounts = 7001
)
The JOIN
version ( recommended ) JOIN
版本( 推荐 )
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.