两个表:
用户:user_info(user_id,user_name)
论文: t_paper(paper_id,paper_user_id)paper_user_id 存放的是多个user_id,用空格隔开的,
查找t_paper 中 用户名称(user_name)中有“张”的记录不知道这条sql怎么写啊,请帮忙!

解决方案 »

  1.   

    select *
    from user_info u,t_paper t
    where FIND_IN_SET(u.user_id,replace(t.paper_user_id,' ',','))
    and user_name like '%张%'
    mysql> select * from user_info;
    +---------+-----------+
    | user_id | user_name |
    +---------+-----------+
    |       1 | 张A1      |
    |       2 | 五A1      |
    |       3 | 请A1      |
    |       4 | 张A2      |
    +---------+-----------+
    4 rows in set (0.00 sec)mysql> select * from t_paper;
    +----------+---------------+
    | paper_id | paper_user_id |
    +----------+---------------+
    |        1 | 1 3 7 99      |
    |        2 | 3 7 999       |
    |        3 | 1 4 7 99      |
    |        4 | 99            |
    +----------+---------------+
    4 rows in set (0.00 sec)mysql>
    mysql> select *
        -> from user_info u,t_paper t
        -> where FIND_IN_SET(u.user_id,replace(t.paper_user_id,' ',','))
        -> and user_name like '%张%';
    +---------+-----------+----------+---------------+
    | user_id | user_name | paper_id | paper_user_id |
    +---------+-----------+----------+---------------+
    |       1 | 张A1      |        1 | 1 3 7 99      |
    |       1 | 张A1      |        3 | 1 4 7 99      |
    |       4 | 张A2      |        3 | 1 4 7 99      |
    +---------+-----------+----------+---------------+
    3 rows in set (0.01 sec)mysql>
      

  2.   

    你也可以用(两边加空格以防止 123 匹配 12)where concat(' ',t.paper_user_id,' ') like concat('% ',u.user_id,' %')where instr(' ',t.paper_user_id,' ') , concat(' ',u.user_id,' ')来代替where FIND_IN_SET(u.user_id,replace(t.paper_user_id,' ',','))
      

  3.   

    不过存在一个问题,paper_id 不是唯一的,虽然可以用group by 过滤,但在count(*) 操作时就不太好处理了
      

  4.   

    试试count(distinct colname) 或者提供一下你的测试数据及基于这个数据的正确结果。
      

  5.   

    我是套了一层select 
    select count(*) from t_paper where paper_id in(select ...)
    虽然有点麻烦,能用就OK啦