1

我有几个表我试图有效地获取数据。

我有一个这样的草拟查询:

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 = ?;

显然这是一个损坏的查询,但我不知道如何解决这个问题。我需要以某种方式将category表连接到通过字段与表product_category相关的表。productsproducts.catalogid

我的微弱尝试是这样的:

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 = ?;

基本上我需要查询 db 以获取 SELECT 子句中类别名称为“NEW”的所有信息......我完全被难住了(我的 SQL 显然需要一些工作!)

4

2 回答 2

2

像这样的东西,只是不断加入和加入......

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"
于 2013-08-06T19:03:09.017 回答
1

由于您有一张product_category表格,因此您的产品似乎可能属于多个类别。在这种情况下,您想检查您正在寻找的类别是否在分配给您的产品的类别中。

一种方法是有一个EXISTS条件:

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 = ?
)

我假设product_category多对多表有列categoryIdproductId这些列汇集了产品的 ID 和该产品所属的类别。

于 2013-08-06T18:59:57.303 回答