2013-08-06 122 views
1

我有幾個表我「米試圖讓數據出有效加入在查詢的WHERE子句

我有一個草擬的查詢這樣:

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

顯然,這是一個破碎的查詢,但我不知道如何解決這個問題,我需要以某種方式加入categoryproduct_category表,該表通過products.catalogid領域涉及products

我愚蠢的嘗試是這樣的:。

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

基本上我需要查詢數據庫的SELECT子句where類別名稱爲「NEW」中的所有信息...,我徹底難倒了(我的SQL顯然需要一些工作!)

+1

不能有muliple'from'的,而不是從某種加入 –

+0

我只是說類似的更換第二: '(加入製造商ON(products.manufacturer = manufacturer.id))(類別JOIN product_category ON ... ... ...)'? – SnakeDoc

+1

只需加入:'在product_category.product = products.id上加入product_category在product_category.Category = category.id'上加入類別。 –

回答

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" 
+0

啊,你是對的,那會丟掉剩餘的行!我刪除了舊評論,這是不正確的。 – dasblinkenlight

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許多一對多表都有一個彙集了產品的ID和類別列categoryIdproductId該產品所屬的產品。