› 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
liujin834
V2EX  ›  MySQL

Mysql select 中嵌套带子句

  •  
  •   liujin834 ·
    liujin834 · Nov 7, 2016 · 6788 views
    This topic created in 3617 days ago, the information mentioned may be changed or developed.

    很常见的用例: 我有一张存放文章的表, tag 字段是逗号分隔的数字,在显示列表的时候我想一次性查询出 tag 的字符串

    SELECT
    	tt.*,u.name,(SELECT group_concat(title) FROM tag WHERE id IN (tt.tag)) as tag
    FROM content tt
    LEFT JOIN user u ON tt.owner=u.id
    ORDER BY ts_created DESC
    

    这句话查出来 tag 每次都是只有一个,原因主要是 IN 语句中放了一个字符串,而不是数字,本来应该是IN(97,92),但这样执行实际上代表了IN('97,92'),请高手帮忙解答一下怎样才能让它变成一串数字用逗号分隔,我知道这样不符合范式什么鬼的,但我这个东西涉及的数据量很小。

    Supplement 1  ·  Nov 7, 2016

    昨晚睡觉前还没想到,稀里糊涂的,早上醒来突然想起来之前用过一个FIND_IN_SET,问题顺利解决

    SELECT
    	tt.*,u.name,(SELECT group_concat(title) FROM tag WHERE FIND_IN_SET(id,tt.tag)) as tag
    FROM content tt
    LEFT JOIN user u ON tt.owner=u.id
    ORDER BY ts_created DESC
    

    改成这样就可以了。

    这个函数的功能是寻找一个字符串是否在另外一个以逗号分割的字符串中存在。

    3 replies  •  2016-11-07 10:21:20 +08:00
    b821025551b
        1
    b821025551b  
       Nov 7, 2016
    写个分割函数。
    SoloCompany
        2
    SoloCompany  
       Nov 7, 2016
    不在乎性能就是 concat(‘,’,id,’,’) like concat(‘%,’,tt.tag,’,%’)
    liujin834
        3
    liujin834  
    OP
       Nov 7, 2016
    @SoloCompany FIND_IN_SET 就解决了哈哈哈
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   758 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 21:29 · PVG 05:29 · LAX 14:29 · JFK 17:29
    ♥ Do have faith in what you're doing.