troubleshooting Question

How to make a like search in multiple tables

Avatar of tim_carter
tim_carter asked on
SQL
7 Comments1 Solution324 ViewsLast Modified:
Hi guys

im a little stuck here and hope someone can help me, im trying to make a LIKE query that look in multiple tables to find some data. Here is the tricky part, even though i want to look in different tables, i only want data from the tables that actually have some data that compares to what the user search for.

I have made this query


SELECT
                  Customers.CustomerId,
                  ParentCompanyNames.CompanyName as ParentCompanyName,
                  Customers.CompanyName,
                  CustomerAssociates.Name,
                  PMBNumbers.PMBNumber,
                  BoxNumbers.BoxNumber,
                  CustomerHandling.MailHandlingScan,
                  CustomerHandling.MailHandlingEmail,
                  CustomerHandling.MailHandlingFax,
                  CustomerHandling.MailHandlingCall,
                  CustomerHandling.MailHandlingSpecial
            FROM
                  Customers
            LEFT JOIN ParentCompanyNames ON Customers.CustomerId=ParentCompanyNames.CustomerId
            LEFT JOIN CustomerAssociates ON Customers.CustomerId=CustomerAssociates.CustomerId
            LEFT JOIN PMBNumbers ON Customers.CustomerId=PMBNumbers.CustomerId
            LEFT JOIN BoxNumbers ON Customers.CustomerId=BoxNumbers.CustomerId
            LEFT JOIN CustomerHandling ON Customers.CustomerId=CustomerHandling.CustomerId
            WHERE
                  Customers.BusinessCenterId = 4
                  AND (Customers.CompanyName like '%test%' OR ParentCompanyNames.CompanyName like '%test%' OR CustomerAssociates.Name like '%test%')
            ORDER BY
                  ParentCompanyName,Name      

But ofcourse this will return rows from all the tables if there is data in them, how do i get around that? Hope you can understand what i mean. Thank you
Join the community to see this answer!
Join our exclusive community to see this answer & millions of others.
Unlock 1 Answer and 7 Comments.
Join the Community
Learn from the best

Network and collaborate with thousands of CTOs, CISOs, and IT Pros rooting for you and your success.

Andrew Hancock - VMware vExpert
See if this solution works for you by signing up for a 7 day free trial.
Unlock 1 Answer and 7 Comments.
Try for 7 days

”The time we save is the biggest benefit of E-E to our team. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange.

-Mike Kapnisakis, Warner Bros