[英]Select rows from table A where string exists in a similar column in table B or table C
I have 3 different SQL tables that I am working with. 我正在使用3个不同的SQL表。 Here is what the table look like:
该表如下所示:
Master Accounts
---------------
CustomerNumber PK
CompanyName
More Columns...
Bill Tos
---------------
MasterCustomerNumber FK
CompanyName
Ship Tos
---------------
MasterCustomerNumber FK
CompanyName
I want to write a MS SQL query that returns all the columns in the Master Accounts table where a company name contains the string 'ama' in any of the three tables. 我想编写一个MS SQL查询,该查询返回“主帐户”表中的所有列,其中公司名称在三个表中的任何一个中都包含字符串“ ama”。
Here is my current SQL: 这是我当前的SQL:
SELECT DISTINCT
MA.*
FROM MasterAccounts MA
LEFT JOIN BillTos BT
ON MA.CustNo = BT.MasterCustNo
LEFT JOIN ShipTos ST
ON MA.CustNo = ST.MasterCustNo
WHERE MA.CompanyName LIKE '%ama%' OR BT.CompanyName LIKE '%ama%' OR ST.CompanyName LIKE '%ama%'
My goal is to get all master accounts where a billto or a shipto companyname contains 'ama'. 我的目标是获取在开单或发货方公司名称中包含“ ama”的所有主帐户。
I read yours comments and maybe this go faster: 我阅读了您的评论,也许这样会更快:
select MA.* from
MasterAccounts MA
join
(select CustNo nmb from MasterAccounts where CompanyName LIKE '%ama%'
union
select MasterCustNo nmb from BillTos where CompanyName LIKE '%ama%'
union
select MasterCustNo nmb from ShipTos where CompanyName LIKE '%ama%' ) num on (num.nmb = MA.CustNo)
if you need more companies maybe you use company name in lower case... 如果您需要更多的公司,也许您使用小写的公司名称...
*if is small error in query i'm sorry - i read this fast.... *如果查询中有小错误,对不起-我读得很快。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.