mysql - 无法在 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 代码不在乎。
请纠正我,如果可能的话,让我知道我错在哪里?
解决方案
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 删除,但它有点复杂。如果您有兴趣,请查看它。
推荐阅读
- if-statement - 传单中基于颜色折线的geojson属性
- jspdf - jspdf Autotable CellHeight 或 RowHeight Auto
- graphql - 不能为不可为空的字段 Subscription.counter 返回 null
- java - React & Java:如何让 accountId(事务表中的外键)填充到数据库中?
- lua - 如何在 LUA 中使用非整数而不使用浮点数
- tensorflow - Colab:将运行时更改为本地后无法运行任何单元格
- javascript - 无法使用 Laravel Mix 加载 popper.js
- html - 如何在 golang 模板中使用对象数组?
- c# - XamarinForms 代码已过时的问题
- html - 如果文件关联设置为 django-html,则 Intellisense for html 不起作用