douguaidian8021 2013-08-29 01:13 采纳率: 100%
浏览 123

Mysql选择10条记录(5种,另5种)

Using Mysql and PHP...

I have a table of ads, ads can be from ad_category "cars" or "general", I need to select 10 rows but make sure I have 5 cars and 5 general records.

Ideally would be if it only finds 3 cars then select 7 general.

Is that done by "SELECT distinct" ? And/or "GROUP BY" ?

  • 写回答

2条回答 默认 最新

  • duanhui1185 2013-08-29 01:16
    关注

    You can do the 5/5 with a union all:

    (select *
     from ads
     where ad_category = 'cars'
     limit 5
    ) union all
    (select *
     from ads
     where ad_category = 'general'
     limit 5
    )
    

    EDIT:

    If you really want 10 records under your circumstances, you can do it with this trick:

    select *
    from ((select *, (@cars_rn := @cars_rn + 1) as rn
           from ads
           where ad_category = 'cars' cross join
                 (select @cars_rn := 0) const
           limit 10
          ) union all
          (select *, (@general_rn = @general_rn + 1) as rn
           from ads
           where ad_category = 'general' cross join
                 (select @general_rn := 0) const
           limit 10
          )
         ) t
    order by rn
    limit 10;
    

    This chooses 10 cars and 10 general, assigning a sequential row number to each. It then orders by the row number and chooses the first 10. This will guarantee 10 records (assuming at least 10 match) and will get a 5/5 split, if possible. Otherwise, it will take all of one and fill in the 10 with the other category.

    评论

报告相同问题?

悬赏问题

  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像
  • ¥15 改算法,照着压缩包里边,参考其他代码封装的格式 写到main函数里
  • ¥15 用windows做服务的同志有吗
  • ¥60 求一个简单的网页(标签-安全|关键词-上传)
  • ¥35 lstm时间序列共享单车预测,loss值优化,参数优化算法
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值