我的产品属于多个类别。
products categories products_categories
------------ ------------- --------------------
product_id category_id product_id
product_title category_title category_id
我想得到n号,可以说是6,最后从每个类别插入不同的产品。我也会在其上加入产品来获取产品信息,但这应该很容易。
我对不同产品的意思是,如果一个产品属于许多类别,它应该只在一个类别中出现一次,而其他类别应该得到另外的n,6个产品,如果可用的话,其他任何可用的产品。
我可以尝试使用等级Select 2 products from each category in MySQL定义的内容 但是当产品属于多个类别时,此解决方案不处理条件,并且我希望每个类别中有不同数量的产品。
这是一些示例数据
pid catid insertion_date
284 48 2/4/2013 1:14:16 AM
278 41 2/4/2013 1:25:03 PM
278 43 2/4/2013 1:25:03 PM
284 45 2/4/2013 12:55:24 PM
284 44 2/4/2013 12:55:24 PM
285 41 2/4/2013 1:28:37 AM
278 42 2/4/2013 1:25:03 PM
285 47 2/4/2013 1:28:42 AM
285 48 2/4/2013 12:50:44 PM
278 46 2/4/2013 1:25:03 PM
278 47 2/4/2013 1:25:03 PM
278 48 2/4/2013 1:25:03 PM
286 43 2/7/2013 3:20:40 PM
286 44 2/7/2013 3:20:40 PM
243 41 2/14/2013 3:30:59 PM
243 42 2/14/2013 3:30:59 PM
243 43 2/14/2013 3:30:59 PM
266 41 2/14/2013 3:51:40 PM
266 47 2/14/2013 3:51:40 PM
266 48 2/14/2013 3:51:40 PM
286 41 2/14/2013 3:51:55 PM
286 42 2/14/2013 3:51:55 PM
286 45 2/14/2013 3:51:55 PM
286 46 2/14/2013 3:51:55 PM
286 47 2/14/2013 3:51:55 PM
286 48 2/14/2013 3:51:55 PM
254 41 2/14/2013 3:52:07 PM
254 43 2/14/2013 3:52:07 PM
254 45 2/14/2013 3:52:07 PM
254 47 2/14/2013 3:52:07 PM
254 48 2/14/2013 3:52:07 PM
252 41 2/14/2013 3:52:23 PM
252 42 2/14/2013 3:52:23 PM
252 45 2/14/2013 3:52:23 PM
252 46 2/14/2013 3:52:23 PM
252 47 2/14/2013 3:52:23 PM
252 48 2/14/2013 3:52:23 PM
169 46 2/14/2013 3:55:54 PM
221 46 2/14/2013 3:56:08 PM
如果有人有更好的解决方案在php中做这些事情,请建议。
答案 0 :(得分:1)
此示例将根据每product_title
的最新product_ID
为您提供2个最新category_title
。
SELECT a.category_title, c.product_title
FROM categories a
INNER JOIN products_categories b
ON a.category_ID = b.category_ID
INNER JOIN products c
ON b.product_ID = c.product_ID
WHERE
(
SELECT COUNT(*)
FROM products_categories d
WHERE b.category_ID = d.category_ID AND
c.product_ID <= d.product_ID
) <= 2
答案 1 :(得分:0)
如果您需要只重复一次重复值,请参阅DISTINCT,它会返回给定列的唯一值的结果。
使用DESC
要限制所需的行数,LIMIT
所以你的最终查询是:
SELECT DISTINCT product_id FROM products_categories ORDER BY product_id DESC LIMIT 6
编辑:尝试实际方式你的意思是,到目前为止无法获得正确的结果,但我相信这对于JOIN
是可行的但是我现在不能只是形成它。我稍后再看看这个,直到那时发现好运,我对这种输出也很好奇,所以将这个添加到收藏夹。
答案 2 :(得分:0)
我的SQL有点生疏,但我想你可以使用NOT IN()删除任何重复项。如果你有一份声明来获得你的前6个产品,那么使用类似的东西:
WITH Statement1 as (SELECT .... FROM ....) -- Get your first 6 products
WITH Statement2 as (SELECT ... FROM .... NOT IN (Statement1)) -- Get 6 new one, NOT in Statement1
... and so on ...
不是最漂亮的代码,但你应该理解我想说的概念。
要获得所有结果,您可以创建一个视图以轻松获取它们:
CREATE VIEW AllProducts AS
Statement1 UNION Statement2 UNION ...;
SELECT .... FROM AllProducts;