【问题标题】:Return random set of rows from a REGEXP query从 REGEXP 查询返回随机行集
【发布时间】:2015-02-13 01:14:55
【问题描述】:

我正在尝试编写一个 MySQL 查询,该查询基于对一组城市的 REGEXP 搜索返回一组随机行。

即...

SELECT * FROM master_rets_table 
          WHERE property_type = "Residential" and city REGEXP "(JUNO BEACH|palm beach gardens|jupiter|WEST PALM BEACH)" and listing_price > 200000 and listing_price < 500000
          GROUP BY city
          ORDER BY RAND()

好消息是,这确实为每个城市返回一个属性,但事实证明,我猜,GROUP BY 消除了查询的 RANdom 方面,因为它每次都给出相同的结果。

【问题讨论】:

  • 不,您看到的GROUP BY 行为是因为MySQL 允许SELECT 中的多个列不在GROUP BY 中。您的查询会在几乎所有其他 RDBMS 中导致语法错误。您能否发布来自master_rets_table 的行示例以及您希望获得的查询输出示例?
  • 你想做什么?
  • master_rets_table有300多个字段,贴出来不太实用。如果可能的话,我试图在一个查询中实现的是获取 4 个随机属性,每个城市在 REGEXP 条件中表示一个。

标签: mysql sql regex random


【解决方案1】:

获得四个随机属性的最简单方法,每个城市一个是使用union all

(select *
 from master_rets_table
 where property_type = "Residential" and city = 'JUNO BEACH' and listing_price > 200000 and listing_price < 500000
 order by rand()
 limit 1
) union all
(select *
 from master_rets_table
 where property_type = "Residential" and city = 'palm beach gardens' and listing_price > 200000 and   listing_price < 500000
 order by rand()
 limit 1
) union all
(select *
 from master_rets_table
 where property_type = "Residential" and city = 'jupiter' and listing_price > 200000 and listing_price < 500000
 order by rand()
 limit 1
) union all
(select *
 from master_rets_table
 where property_type = "Residential" and city = 'WEST PALM BEACH' and listing_price > 200000 and  listing_price < 500000
 order by rand()
 limit 1
)

【讨论】:

  • hmmm 非常有趣...我从来没有使用过 UNION ALL 所以这个答案不仅是正确的,它还教会了我一些新的东西。谢谢!
猜你喜欢
  • 1970-01-01
  • 2021-08-01
  • 1970-01-01
  • 2019-02-01
  • 2010-12-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-18
相关资源
最近更新 更多