我有两个表,产品和属性。每个产品都有很多属性!
当我必须找到具有多个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小提琴 - 可能会更容易http://sqlfiddle.com/#!2/b3ada0
答案 0 :(得分: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
答案 1 :(得分: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