简体   繁体   中英

SQL Query between three tables, get data only from one table

I have these 3 tables:

product table

id

siteId

optionsSet table

id

productId

...

option table

id

optionsSetId

code

...

Question:

How can I make a SQL query to select all from option table by knowing these two: option.code and product.siteId ?

I know how to do a query with JOIN on two tables, but I am struggling with joining these three tables.

Something like

SELECT
    *
FROM
    option
WHERE
    code = @code
    AND optionsSetId IN 
    (SELECT
        os.id
    FROM
        optionsSet os
        JOIN product p ON os.productId = p.Id
    WHERE
        p.siteId = @siteId)

where @code is your code parameter and @siteId is your siteid parameter

to use inner joins you would have to join all 3 tables together and that would like

SELECT 
    DISTINCT o.* 
FROM
    option o
    JOIN optionsSet os ON o.optionsSetId = os.Id
    JOIN product p ON os.productId = p.Id
WHERE
    o.code = @code
    AND p.siteId = @site

if you notice that requires a DISTINCT to only get the data from option . It may be simpler and easier to understand but not very efficient.

another option that someone will probably say is way more awesome is using EXISTS

SELECT
    o.*
FROM
    OPTION o
WHERE
    o.code = @code
    AND EXISTS(
        SELECT
            1
        FROM
            optionsSet os
            JOIN product p ON os.productId = p.Id
        WHERE
            o.optionSetId = os.Id
            AND p.siteId = @siteId
    )

I used EXISTS exclusively for a few years and the started working on databases with tables that had +100million records and IN was faster than EXISTS in some cases and identical in the others. Plus IN is less code.

SELECT * FROM option
LEFT JOIN product
ON option.code = product.siteId (+)

--(+) is a left outter join. This should include all of the values in option.code and all of the values in product that have the same siteId as values in option.

I'm unsure on how you want OptionSet to relate to the other 2 databases though?

if you want to include the third tables result you can just add another join on that table for the condition you want.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM