V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
MySQL 5.5 Community Server
MySQL 5.6 Community Server
Percona Configuration Wizard
XtraBackup 搭建主从复制
Great Sites on MySQL
Percona
MySQL Performance Blog
Severalnines
推荐管理工具
Sequel Pro
phpMyAdmin
推荐书目
MySQL Cookbook
MySQL 相关项目
MariaDB
Drizzle
参考文档
http://mysql-python.sourceforge.net/MySQLdb.html
mxm145
V2EX  ›  MySQL

求一个 sql 语句或解决办法

  •  
  •   mxm145 · 2020-09-29 14:49:04 +08:00 · 2075 次点击
    这是一个创建于 1276 天前的主题,其中的信息可能已经有所发展或是发生改变。

    有两个表 A,B 。A 表存的文章标题、发布时间这些信息,B 表存的是文章的内容,两个表的 ID 是一致的。现在的问题是:有关键词搜索的时候先在 A 表的标题里面进行搜索,再到 B 表的文章内容字段里面进行搜索,最后要把两个结果合并起来再按照 A 表的发布时间进行倒排。用了 SQL 的 union 搜索,在排序的时候就会把两个结果混合在一起,需要把 A 表的搜索结果按照时间排序放在前面,不知道各位有没有啥办法。

    8 条回复    2020-09-30 14:35:25 +08:00
    RedBeanIce
        1
    RedBeanIce  
       2020-09-29 14:56:36 +08:00
    感觉内容搜索,标题搜索,已经是 ES ????
    LeeSeoung
        2
    LeeSeoung  
       2020-09-29 14:59:25 +08:00
    A 排序 union all B 排序
    DonaldY
        3
    DonaldY  
       2020-09-29 15:02:43 +08:00
    查询 sql 时,多加个字段来标识数据源来自哪,order by 这个字段。
    jiorix
        4
    jiorix  
       2020-09-29 15:03:44 +08:00
    select aa.*
    from
    (
    select a.*, 1 as queryType
    from a
    where title like '%关键字%'
    union
    select a.*, 2 as queryType
    from a
    where a.id in (
    select id from b where content like '%关键字%'
    )
    ) as aa
    order by queryType, ....
    mxm145
        5
    mxm145  
    OP
       2020-09-29 15:22:00 +08:00
    @RedBeanIce 还是 mysql,没有用 es
    @LeeSeoung 我查了 union 没办法用两个 order
    @jiorix 多谢大佬的代码,思路我懂了

    多谢各位的回复
    liuky
        6
    liuky  
       2020-09-30 08:37:37 +08:00
    select a.*
    from A as a
    inner join B as b on a.id = b.id
    where a.title like '%key%' and b.content like '%key%'
    order by a.createtime desc
    mxm145
        7
    mxm145  
    OP
       2020-09-30 14:32:58 +08:00
    @liuky 这个跑出来的数据是 title 和 content 都有关键词的结果,我想要的是只要两个其中一个的都要显示出来,而且按照 title 匹配到的在前面,content 匹配到的在后面。如果把你的 and 改成 or 的话也不行
    mxm145
        8
    mxm145  
    OP
       2020-09-30 14:35:25 +08:00
    我最后使用的是两个子查询 union 来实现的,参考这个: https://www.jianshu.com/p/2a53c2fdb042
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3365 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 29ms · UTC 00:05 · PVG 08:05 · LAX 17:05 · JFK 20:05
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.