Solved

Verify SQL multiple inner joins

Posted on 2014-07-24
7
228 Views
Last Modified: 2014-07-25
I created a search query on my site a while back that has been working quite well  it looks like this:
SELECT products.idProduct, products.sku, products.description, products.price, products.listhidden, products.listprice, products.serviceSpec, products.bToBPrice, products.smallImageUrl,products.noprices,products.stock, products.noStock,products.pcprod_HideBTOPrice, (0) as POrder ,products.FormQuantity,products.pcProd_BackOrder FROM products WHERE (((description LIKE '%wal%') OR (SKU LIKE 'wal%'))) AND (active=-1 AND removed=0 AND configOnly = 0 AND listprice > 0 AND description <> '') ORDER BY sku ASC, idproduct DESC

Open in new window


We discovered the results were including products that were in hidden categories.  The structure of the database is like this:  idProduct is the key for the products table, and idCategory is the key for the categories table.  categories_products is the table that connects the product table to the category table, since products can be assigned to multiple tables.

Since all the configuration for a category is in the categories table, I need to link products to the categories_product table and then to the categories table to determine if the category should be visible or not. (categories.ibtoHide = 0 is the value i need to check for)

I came up with this:
SELECT products.idProduct, products.sku, products.description, products.price, products.listhidden, products.listprice, products.serviceSpec, products.bToBPrice, products.smallImageUrl,products.noprices,products.stock, products.noStock,products.pcprod_HideBTOPrice, (0) as POrder ,products.FormQuantity,products.pcProd_BackOrder FROM products inner join categories_products on products.idProduct = categories_products.idProduct inner join categories on categories_products.idCategory = categories.idCategory WHERE categories.ibtoHide = 0 and (((description LIKE '%wal%') OR (SKU LIKE 'wal%'))) AND (active=-1 AND removed=0 AND configOnly = 0 AND listprice > 0 AND description <> '') ORDER BY sku ASC, products.idproduct DESC

Open in new window


This works well, but it duplicates everything.  Adding "distinct" solves that, but I'm a little concerned that this isn't the most efficient way to write the query.  Is there a way to do it without getting duplicates?

Thanks for your help!!!
0
Comment
Question by:slightlyoff
7 Comments
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40217883
Please format your code as it makes it easier to read.  I also aliased the tables

SELECT p.idProduct, p.sku, p.description, p.price, p.listhidden, p.listprice, p.serviceSpec, p.bToBPrice, p.smallImageUrl,p.noprices,p.stock, p.noStock,p.pcprod_HideBTOPrice, (0) as POrder ,p.FormQuantity,p.pcProd_BackOrder
FROM products p
inner join categories_products cp on p.idProduct = cp.idProduct 
inner join categories c on cp.idCategory = c.idCategory 
WHERE c.ibtoHide = 0 and (((description LIKE '%wal%') OR (SKU LIKE 'wal%'))) AND (active=-1 AND removed=0 AND configOnly = 0 AND listprice > 0 AND description <> '') 
ORDER BY sku ASC, products.idproduct DESC

Open in new window


If the products can be in more than 1 category distinct is the only way to get around it.
0
 
LVL 26

Expert Comment

by:Shaun Kline
ID: 40217884
You can avoid the joins by adding a condition to your WHERE clause that eliminates products that are included in categories that are hidden.

The added condition would be:
WHERE NOT EXISTS (SELECT 1 FROM categories_products inner join categories on categories_products.idCategory = categories.idCategory WHERE categories.ibtoHide = 0 and products.idProduct = categories_products.idProduct)
AND ...
0
 
LVL 69

Accepted Solution

by:
Scott Pletcher earned 500 total points
ID: 40218006
You had good instincts on this: DISTINCT is not the way to go.

Since you're joining only to verify a match, as all the columns you list are from the Products table, you should use EXISTS() instead of a JOIN.  This prevents extra duplicate rows from being generated in the first place, so DISTINCT will not be needed.

Something like this:


SELECT
    p.idProduct, p.sku, p.description, p.price, p.listhidden,
    p.listprice, p.serviceSpec, p.bToBPrice, p.smallImageUrl, p.noprices,
    p.stock, p.noStock, p.pcprod_HideBTOPrice, (0) as POrder , p.FormQuantity,
    p.pcProd_BackOrder
FROM products p
WHERE
    ((p.description LIKE '%wal%') OR (p.SKU LIKE 'wal%')) AND
    (p.active=-1 AND p.removed=0 AND p.configOnly = 0 AND p.listprice > 0 AND p.description > '') AND
    EXISTS (
        SELECT 1
        FROM categories_products cp
        INNER JOIN categories c ON
            cp.idCategory = c.idCategory
        WHERE
            cp.idProduct = p.idProduct AND
            c.ibtoHide = 0
    )
ORDER BY
    sku ASC, idproduct DESC
0
Back Up Your Microsoft Windows Server®

Back up all your Microsoft Windows Server – on-premises, in remote locations, in private and hybrid clouds. Your entire Windows Server will be backed up in one easy step with patented, block-level disk imaging. We achieve RTOs (recovery time objectives) as low as 15 seconds.

 
LVL 1

Author Comment

by:slightlyoff
ID: 40218119
Thank you very much for the feedback!  I'm glad i asked :)
I'll be back in the office tomorrow to verify and test these solutions, but i wanted to post and let you know i appreciate the help.
0
 
LVL 1

Author Comment

by:slightlyoff
ID: 40218122
Also, thanks Kyle, I should have considered how the SQL looked first - and I will make sure to do that in the future.
0
 
LVL 40

Expert Comment

by:Kyle Abrahams
ID: 40218167
Yeah . . . the exists is the way to go . . . can't believe I missed that one.  A bit scatter brained today.
0
 
LVL 1

Author Closing Comment

by:slightlyoff
ID: 40219793
Thanks so much for your help.   I've learned SQL as I've gone along - learning SELECT, UPDATE, DELETE, inner join, etc.  It isn't until I come across stuff like this that I realize I could do a lot more.  I didn't even know an EXISTS statement existed :)  - now I do.

Thank you again!
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
How to share SSIS Package? 6 37
SSRS 2013 - Overlapping reports 2 22
Email Header Detail 12 55
VB.net and sql server 4 35
Composite queries are used to retrieve the results from joining multiple queries after applying any filters. UNION, INTERSECT, MINUS, and UNION ALL are some of the operators used to get certain desired results.​
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
This video shows, step by step, how to configure Oracle Heterogeneous Services via the Generic Gateway Agent in order to make a connection from an Oracle session and access a remote SQL Server database table.
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.

773 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question