首页 > 解决方案 > 无法在 Rails 中重现(1 对 1)Mysql 查询

问题描述

我正在尝试将 mysql 查询搜索重现到 rails (AR) 模型代码中。我在互联网上尝试了几个帖子,但没有一个对我有用。

这是mysql查询:

SELECT id, title, content, created_at, match(title) against ('alpha' in natural language mode) AS score FROM users.hubspot_blog_posts where match(title) against ('alpha' in natural language mode) order by score desc, created_at desc;

这个想法是获取与搜索模式匹配的所有标题并对其进行排序,首先按分数,其次(如果分数相等)按 created_at 日期。

虽然上面的查询似乎可以按我的意愿工作,但我无法将其转换为 rails 代码。这是我尝试过的,我得到了相同的集合但不同的oredre:

HubspotBlogPost.select("*, MATCH(title) AGAINST ('alpha' in natural language mode) AS score").where("MATCH(title) AGAINST('alpha' in natural language mode)", :order => "score desc, created_at desc")

使用 Mysql,如果score相同,则按日期(created_at)进行订单,但 ruby​​ 代码不在乎。

请纠正我,如果可能的话,让我知道我错在哪里?

标签: mysqlruby-on-railsactiverecord

解决方案


Order by 不是一种选择,where()它是一种独立的方法。

HubspotBlogPost.select(
  "*, MATCH(title) AGAINST ('alpha' in natural language mode) AS score"
).where(
  "MATCH(title) AGAINST('alpha' in natural language mode)"
).order(
  "score desc, created_at desc"
).to_sql

返回

SELECT *, MATCH(title) AGAINST ('alpha' in natural language mode) AS score FROM "customers" WHERE (MATCH(title) AGAINST('alpha' in natural language mode)) ORDER BY score desc, created_at desc

通过避免使用直接 SQL,可以使这看起来更好、更安全。

HubspotBlogPost.select(
  HubspotBlogPost.arel_table[Arel.star],
  "MATCH(title) AGAINST ('alpha' in natural language mode) AS score"
).where(
  "MATCH(title) AGAINST('alpha' in natural language mode)"
).order(
  'score desc', created_at: :desc
).to_sql

最后一个原始 sql 也可以使用 Arel 删除,但它有点复杂。如果您有兴趣,请查看它。


推荐阅读