2013-02-09 105 views
0

我的表格名爲Products,因爲type是字段type值可能是這些值中的任何一個1,2,3,4根據字段限制MySQL結果

現在I'would希望得到的結果作爲

1. Group the results based on 'type' 
2. And Limit the results for each group to 5. 

我怎樣才能做到這一點,目前我使用下面的查詢

SELECT 
    *, 
    (
    (
     CASE 
    WHEN product_title LIKE '%xyz%' 
    THEN 2 
    ELSE 0 
     END 
    ) + (
     CASE 
    WHEN product_description LIKE '%xyz%' 
    THEN 1 
    ELSE 0 
     END 
    ) 
) AS relevance 
FROM 
    Products 
WHERE (
    (
     product_title LIKE '%xyz%' 
     OR product_description LIKE '%xyz%' 
    ) 
) 
    AND product_available = 1 
    AND product_deleted <> 1 
ORDER BY relevance DESC 
+0

其中是樣本數據和期望的輸出? – 2013-02-09 11:43:54

回答

0
SELECT * FROM products; 
+------------+------+ 
| product_id | type | 
+------------+------+ 
|   1 | 4 | 
|   2 | 3 | 
|   3 | 2 | 
|   4 | 4 | 
|   5 | 3 | 
|   6 | 1 | 
|   7 | 4 | 
|   8 | 3 | 
|   9 | 4 | 
|   10 | 2 | 
|   11 | 2 | 
|   12 | 1 | 
|   13 | 3 | 
|   14 | 2 | 
|   15 | 3 | 
|   16 | 1 | 
|   17 | 2 | 
|   18 | 1 | 
|   19 | 2 | 
|   20 | 4 | 
|   21 | 2 | 
+------------+------+ 

SELECT x.* 
    FROM products x 
    JOIN products y 
    ON y.type = x.type 
    AND y.product_id <= x.product_id 
    GROUP 
    BY x.product_id 
HAVING COUNT(*) <=3 
    ORDER 
    BY type 
     , product_id; 
+------------+------+ 
| product_id | type | 
+------------+------+ 
|   6 | 1 | 
|   12 | 1 | 
|   16 | 1 | 
|   3 | 2 | 
|   10 | 2 | 
|   11 | 2 | 
|   2 | 3 | 
|   5 | 3 | 
|   8 | 3 | 
|   1 | 4 | 
|   4 | 4 | 
|   7 | 4 | 
+------------+------+ 
0

這裏有一個簡單的

SELECT 
p.id, 
p.type 
FROM 
Products p 
WHERE 
5 > (SELECT COUNT(id) from Products where id < p.id and type = p.type) 

我已經爲我創建了sqlfiddle t,http://sqlfiddle.com/#!2/ab0c00/15