【问题标题】:how to random select row in one table according to each row in other table?如何根据另一个表中的每一行随机选择一个表中的行?
【发布时间】:2018-05-07 09:56:44
【问题描述】:

有2个表:

crashtraffic_flow

crash 表的属性为crash_datetime,以及对应的检测器ID

探测器记录的traffic_flow表有date,time,detector_ID属性,自增id和流量参数。

现在我愿意在traffic_flow中为崩溃的每一行分别随机选择10行并将它们插入到一个新表中。

以下是试用:

select traffic_flow.id
from traffic_flow,crash
where traffic_flow.date=crash.date and traffic_flow.ID=crash.ID
order by rand()
limit 10;

但是这条sql语句一共选择了10行所有的crash记录,而不是crash中的每一行,所以不能满足我的要求。你能帮我修改一下声明吗?

【问题讨论】:

  • 今日提示:切换到现代、明确的JOIN 语法。更容易编写(没有错误),更容易阅读(和维护),并且在需要时更容易转换为外连接。
  • 添加一些示例表数据和预期结果 - 格式化文本,而不是图像。 (提示:3 小于 10,但仍然是同样的问题。)

标签: mysql sql


【解决方案1】:

在 MySQL 中,最简单的方法是使用变量来枚举每次崩溃的行:

select *
from (select ct.*,
             (@rn := if(@ct = id, @rn + 1,
                        if(@ct := id, 1, 1)
                       )
             ) as rn
      from (select c.*, tf.id as tf_id
            from traffic_flow tf join
                 crash c
                 on tf.date = c.date and tf.ID = c.ID
            order by c.id, rand()
           ) ct cross join
           (select @cid := -1, @rn := 0) params
     )
where rn <= 10;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2020-02-16
    • 2017-02-11
    • 2020-07-28
    • 1970-01-01
    • 2020-05-27
    • 2012-11-23
    相关资源
    最近更新 更多