我有几张桌子,我试图有效地获取数据。
我有一个草拟的查询:
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
表,该表通过products
字段与products.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 = ?;
基本上我需要在数据库中查询类别名称为“NEW”的SELECT子句中的所有信息...而且我完全被难倒了(我的SQL显然需要一些工作!)
答案 0 :(得分: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"
答案 1 :(得分: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
多对多表格包含categoryId
和productId
列,它们汇集了产品的ID和该产品所属的类别。