I have 3 different SQL tables that I am working with. 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.
Here is my current 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'.
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....
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.