› 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 · Sep 29, 2020 · 3387 views
    This topic created in 2188 days ago, the information mentioned may be changed or developed.

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

    8 replies  •  2020-09-30 14:35:25 +08:00
    RedBeanIce
        1
    RedBeanIce  
       Sep 29, 2020
    感觉内容搜索,标题搜索,已经是 ES ????
    LeeSeoung
        2
    LeeSeoung  
       Sep 29, 2020
    A 排序 union all B 排序
    DonaldY
        3
    DonaldY  
       Sep 29, 2020
    查询 sql 时,多加个字段来标识数据源来自哪,order by 这个字段。
    jiorix
        4
    jiorix  
       Sep 29, 2020
    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
       Sep 29, 2020
    @RedBeanIce 还是 mysql,没有用 es
    @LeeSeoung 我查了 union 没办法用两个 order
    @jiorix 多谢大佬的代码,思路我懂了

    多谢各位的回复
    liuky
        6
    liuky  
       Sep 30, 2020
    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
       Sep 30, 2020
    @liuky 这个跑出来的数据是 title 和 content 都有关键词的结果,我想要的是只要两个其中一个的都要显示出来,而且按照 title 匹配到的在前面,content 匹配到的在后面。如果把你的 and 改成 or 的话也不行
    mxm145
        8
    mxm145  
    OP
       Sep 30, 2020
    我最后使用的是两个子查询 union 来实现的,参考这个: https://www.jianshu.com/p/2a53c2fdb042
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   824 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 33ms · UTC 21:06 · PVG 05:06 · LAX 14:06 · JFK 17:06
    ♥ Do have faith in what you're doing.