简体   繁体   中英

Join in Query WHERE clause

I have several tables I"m trying to get data out of efficiently.

I have a drafted query as such:

SELECT products.id, products.name products.extended_description, products.catalogid, products.image1, products.image2, products.stock, products.price, manufacturer.manufacturer, products.weight
FROM products 
JOIN manufacturer ON (products.manufacturer = manufacturer.id)
WHERE category.category_name = ?;

Obviously this is a broken query, but I'm not sure how to fix this. I need to somehow join category table to product_category table which is related to products table via the products.catalogid field.

My feeble attempt is as such:

SELECT products.id, products.name products.extended_description, products.catalogid, products.image1, products.image2, products.stock, products.price, manufacturer.manufacturer, products.weight
FROM products
JOIN manufacturer ON (products.manufacturer = manufacturer.id)
FROM category
JOIN product_category ON (category.id = (SELECT product_category.id FROM product_category WHERE product_category.catalogid /*I'm so lost...*/))
WHERE category.category_name = ?;

Basically I need to query the db for all the info in the SELECT clause where the category name is "NEW"... and I'm completely stumped (my SQL obviously needs some work!)

Something like this, just keeping joining and joining and....

SELECT
    *
FROM
    products as p
JOIN
    manufacturer as m
ON
    p.manufacturer = m.id
JOIN
    product_category as pc
ON
    pc.product = p.id
JOIN
    category as c
ON
    c.id=pc.category
WHERE
    c.name = "NEW"

Since you've got a product_category table, it appears that your product may belong to multiple categories. In cases like that, you want to check if a category that you are looking for is among the categories assigned to your product.

One way of doing it is with an EXISTS condition:

SELECT p.id, p.name p.extended_description, p.catalogid, p.image1, p.image2, p.stock, p.price, m.manufacturer, p.weight
FROM products p
JOIN manufacturer m ON (p.manufacturer = m.id)
WHERE
EXISTS (
    SELECT *
    FROM product_category pc
    JOIN category c ON c.id=pc.categoryId
    WHERE pc.productId = p.id
    AND c.category.category_name = ?
)

I assumed that the product_category many-to-many table has columns categoryId and productId which bring together the IDs of the product and a category to which that product belongs.

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