0

フィールド値がこれらの値のいずれかである可能性があるというテーブルを呼び出しProductsました。typetype1,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 に答える