如何根据另一个表上的参考数据过滤一个表上的数据?

时间:2015-05-20 16:46:24

标签: sql sql-server sql-server-2000

我有两张表account_agentbulk_index。每个表的数据如下

account_agent

name         code         account         remark         scheme
avi          10           151362          first          as
babi         11           123478          new            as
avi          10           151721          new            as
avi          10           151765          new            as
sam          sas/01       925458          tin            sas

bulk_index

agentcode         account          customer_name
10                151362           Alok
22                265721           Rohan
10                151721           Akash

使用这些表我想在account_agent表上得到如下结果

account_agent

name         code         account         remark
avi          10           151362          first
avi          10           151721          new

我已经尝试了查询

select * from account_agent where code = '10' and account = (select account from bulk_index where code = '10')

4 个答案:

答案 0 :(得分:2)

这个查询对我有用

SELECT A.name, A.code, A.Account, A.remark, A.scheme
FROM account_agent A
INNER JOIN bulk_index B ON A.account = B.account 
WHERE A.scheme = 'as' AND A.code = '10'

答案 1 :(得分:0)

这将只返回bulk_index表中相关的数据:

SELECT A.name, A.code, A.Account, A.remark
FROM account_agent A
INNER JOIN bulk_index B
   ON A.account = B.account AND A.code = B.agentcode

答案 2 :(得分:0)

假设您的account列是唯一的,您可以只执行一个简单的连接和一个where子句来获取此内容:

SELECT A.name, A.code, A.Account, A.remark
FROM account_agent A
INNER JOIN bulk_index B ON A.account = B.account 
WHERE a.scheme like '%as%' and a.code = '10' 
--remove the preceeding or succeeding % in like as needed

如果您只对scheme列等于'as'并且code等于10的值感兴趣,那么您可以这样做:

SELECT A.name, A.code, A.Account, A.remark
FROM account_agent A
INNER JOIN bulk_index B ON A.account = B.account 
WHERE a.scheme = 'as' and a.code = '10'

以下是W3Schools页面的链接,该页面解释了在sql中使用like运算符。

SQL LIKE Operator

答案 3 :(得分:0)

select name,code,account,remark
from account_agent
where exists(select bulk_index.agentcode from bulk_index where bulk_index.agentcode = account_agent.code)

此代码将显示bulk_index表格中存在的account_agent表代码的所有数据 agentcode