[英]one product in many categories, finding n number of products from each category - php mysql
我有屬於多個類別的產品。
products categories products_categories
------------ ------------- --------------------
product_id category_id product_id
product_title category_title category_id
我想獲得n個數字,可以說6個,是每個類別中最后插入的不同產品。 我也將加入產品的連接以獲取產品信息,但是這應該很容易。
我從不同產品中獲得的意思是,如果一個產品屬於多個類別,則在一個類別中它應該只出現一次,而其他類別應獲得n個,6個產品(如果有)。
我可以嘗試使用在MySQL中從每個類別中選擇2個產品的排名來定義此處的內容,但是當產品屬於多個類別時,此解決方案無法處理這種情況,並且我希望每個類別中有n種不同的產品。
這是一些樣本數據
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中進行此類操作,請提出建議。
本示例將根據每個category_title
最新product_ID
為您提供2個最新product_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
我的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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.