简体   繁体   中英

Mysql Query - join, subquery, if exists

I am struggling with a query. I just can't wrap my head around it.

I have 4 tables: Inventory, style, sizes, style_sizes

Inventory contains columns user_id, style, size etc. Style contains columns: style_id, style (the name of the style) etc. Sizes contains columns: size_id, size, etc. (sm, md, lg, etc) style_sizes contains columns: style_size_id, style_id, size_id (this is to list the sizes available for selected style)

What i need is to list all inventory for user_id = x and style = y (not style_id) where the user has the size and to order by size_id.

Currently, it is showing for all sizes that are available for that style even if the user does not have any.

Here is query so far...

SELECT i.*, st.*, ss.* 
            FROM inventory as i
            JOIN style as st
            ON i.style = st.style
            JOIN style_sizes as ss
            ON st.style_id = ss.style_id
            WHERE i.user_id = $user_id AND i.style = :style

I am close but I am not sure where to go from here. Thanks in advanced.

You need to include the size_id in the join so you only get the sizes for that user.

SELECT i.*, st.*, ss.* 
FROM inventory as i
JOIN style as st
    ON i.style = st.style
JOIN style_sizes as ss
    ON st.style_id = ss.style_id AND i.size_id = ss.size_id
WHERE i.user_id = :user_id AND i.style = :style

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