使用计数器混合结果从mysql中选择

时间:2014-07-14 17:21:56

标签: mysql

我想从表格中选择产品。 数据将根据product_rank进行排序 但是,即使排名不够好,每个3或5个产品我想从同一张桌子中选择另一个产品与高价(CPC)! 假设该表只有4个字段:

ID         Title          Rank          CPC

有人知道如何用一个couter来实现这个目标我在哪里定义它应该显示多少产品的高价?

感谢您的帮助

编辑: 这里有一些示例数据

1        shoes A        500    0.4
2        shoes B        0      0.9
3        shoes C        480    0.5
4        shoes D        600    0.3
5        shoes E        550    0.4
6        shoes F        300    0.5
7        shoes G        80     0.8
8        shoes H        800    0.35
9        shoes I        100    0.8
10       shoes J        900    0.4

假设我想在每三个位置展示高价竞标者。例外结果如下

shoes J (best rank)
shoes H (2nd best rank)
shoes B (1st highbidder)
shoes D (3rd best rank)
shoes E (4th best rank)
shoes I (2nd highbidder and better rank than G!!)

等...

如果可能,它应该只有一个选择语句。 谢谢

2 个答案:

答案 0 :(得分:0)

SELECT * FROM tbl LIMIT 5;     # Retrieve first 5 rows
SELECT * FROM tbl LIMIT 5,10;  # Retrieve rows 6-15

可以用来告诉它你先前选择了其中的5个并且想要接下来的10个,或者其他什么。

答案 1 :(得分:0)

做那个特定的排序并不容易...这需要一点点摆弄,但会做你想要的...它按2级排序然后1 cpc按最大排名和cpc排序。

SELECT * FROM(
    (SELECT 
        id, title, rank AS my_rank, count_col
    FROM
        (SELECT 
            id, title, rank, @C:=@C + 1 AS testing,
            IF(@C MOD 3 = 0, @C:=@C + 1, @C) AS count_col
        FROM
            products
        CROSS JOIN (SELECT @C:=0) t
        ORDER BY rank DESC) AS temprank) 
    UNION 
    (SELECT 
        id, title, cpc AS my_rank, count_col
    FROM
        (SELECT 
            id, title, cpc, @B:=@B + 3 AS count_col
        FROM
            products
        CROSS JOIN (SELECT @B:=0) t
        ORDER BY cpc DESC) tempcpc) 
    ORDER BY count_col
    ) as total_rows
group by id
order by count_col

DEMO

示例输出。 http://screencast.com/t/uMSPU9IiEyg6