cakephp分页与复杂的查询

时间:2016-01-28 10:14:27

标签: php mysql cakephp pagination cakephp-2.5

我有一个数据库结构,如下所示

id | Title   | brand | 
---+---------+-------+
1  |product1 | Lg    |
2  |pruduct2 | Lg    |
3  |pruduct3 | Lg    |
4  |pruduct4 | Lg    |
5  |pruduct5 | Lg    |
6  |pruduct6 |samsung|
7  |pruduct7 |samsung|
8  |pruduct8 |samsung|
9  |pruduct9 |samsung|
10 |pruduct10|samsung|
11 |pruduct11| sony  |
12 |pruduct12| sony  |
13 |pruduct13| sony  |
14 |pruduct14| sony  |
15 |pruduct15| sony  |

我们需要一些查询,我可以根据品牌来混合结果 输出应该像

id | Title   | brand | 
---+---------+-------+
1  |product1 | Lg    |
6  |pruduct6 |samsung|
11 |pruduct11| sony  |
2  |pruduct2 | Lg    |
7  |pruduct7 |samsung|    
12 |pruduct12| sony  |
.... and so on

我有以下查询可以检索相同的结果

select id, title,brand row_number() over (partition by brand_id) as 
row_num from product_test order by row_;

遗憾的是,这不适用于MySql 需要基于cakephp find或任何其他apporach的解决方案

提前致谢

1 个答案:

答案 0 :(得分:0)

您可以通过以下方式模拟查询:

SELECT @rownum := 0, @brand := NULL;

SELECT
  id
, title
, brand
FROM (
  SELECT
    id
  , title
  , brand
  , @rownum := IF(@brand <=> brand, @rownum + 1, 1) AS row_num
  , @brand := brand AS dummy
  FROM
    product_test
  ORDER BY
    brand
  , id
  ) product_test
ORDER BY
  row_num
, brand
, id;