Solved

Verify SQL multiple inner joins

Posted on 2014-07-24
7
230 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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
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!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

Question has a verified solution.

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

Suggested Solutions

Confronted with some SQL you don't know can be a daunting task. It can be even more daunting if that SQL carries some of the old secret codes used in the Ye Olde query syntax, such as: (+)     as used in Oracle;     *=     =*    as used in Sybase …
International Data Corporation (IDC) prognosticates that before the current the year gets over disbursing on IT framework products to be sent in cloud environs will be $37.1B.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.

789 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