0

我已经调用Products了表,即type字段type值可能是这些值中的任何一个1,2,3,4

现在我想得到结果

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 
4

2 回答 2

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,http: //sqlfiddle.com/#!2/ab0c00/15

于 2013-02-09T13:48:24.390 回答
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 |
 +------------+------+
于 2013-02-09T11:49:22.870 回答