根据字段限制MySQL结果

时间:2013-02-09 11:41:09

标签: mysql sql

我的名为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 

2 个答案:

答案 0 :(得分: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 |
 +------------+------+

答案 1 :(得分: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