0

我有两个表,产品和属性。每个产品可以有很多pattributes!

当我必须找到具有多个 pattributes 的产品时,问题就开始了。

select * from `products` 
left join `pattributes` on `pattributes`.`products_id` = `products`.`id` 
where `products`.`status` = 1 
AND `products`.`sold` = 0 
AND `products`.`deleted` = 0 
AND `products`.`categories_id` = 30 
AND `pattributes`.`attributes_id` = 5 
AND `pattributes`.`values_id` = 10 
AND `pattributes`.`attributes_id` = 4 
AND `pattributes`.`values_id` = 15 
group by `products`.`id` 
order by `products`.`top` desc, 
`products`.`id` desc

因此,如果我正在寻找两个或更多 pattributes 它返回 0 行。但是,如果我寻找一个 pattribute 它工作正常。

我不是 mysql 大师,不确定我是否必须使用左连接。也许有人知道最好的解决方案?

添加了 SQL Fiddle - 也许会更容易http://sqlfiddle.com/#!2/b3ada0

4

2 回答 2

0

用于IN()多个 pattributes 并且与多个相同values_id

select * from `products` 
left join `pattributes` on `pattributes`.`products_id` = `products`.`id` 
where `products`.`status` = 1 
AND `products`.`sold` = 0 
AND `products`.`deleted` = 0 
AND `products`.`categories_id` = 30 
AND `pattributes`.`attributes_id` IN(5 ,4)// if type is varchar then IN('5' ,'4')
AND `pattributes`.`values_id` IN( 10,15 )
group by `products`.`id` 
order by `products`.`top` desc, 
`products`.`id` desc
于 2013-09-23T12:59:40.830 回答
0

最后在一些朋友的帮助下让它工作:

SELECT 
    * 
FROM 
    `products`
WHERE 
    `products`.`status` = 1 
    AND `products`.`sold` = 0 
    AND `products`.`deleted` = 0 
    AND `products`.`categories_id` = 30
    AND 
    (
        (SELECT 
             COUNT(*) 
         FROM `pattributes`
         WHERE 
             `pattributes`.`products_id` = `products`.`id`
             AND 
             (
                 (
                   `pattributes`.`attributes_id` = 4
                   AND `pattributes`.`values_id` = 14
                 )
                 OR
                 (
                   `pattributes`.`attributes_id` = 5
                   AND `pattributes`.`values_id` = 10
                 )
             )
         ) = 2

    )
GROUP BY `products`.`id`
ORDER BY `products`.`top` DESC, `products`.`id` DESC    
于 2013-09-23T22:16:10.927 回答