各位好!:)
我有一问题想请教。数据库使用mysql。譬如我有如下两张表:mysql> select * from a1;
+--------+
| id     |
+--------+
| 张三千 |
| 李四万 |
| 王五   |
| 茅十八 |
| 马六   |
+--------+
mysql> select * from b1;
+----+
| id |
+----+
| 三 |
| 五 |
| 四 |
+----+我想把a1.id中含有b1.id的值的记录找出来,这相当于对b1.id的值分别做like查询:
select * from a1 where a1.id like '%三%' UNION select * from a1 where a1.
id like '%四%'  UNION select * from a1 where a1.id like '%五%';最后想要得到下面的效果+--------+
| id     |
+--------+
| 张三千 |
| 李四万 |
| 王五   |
+--------+我尝试用select * from a1,b1 where a1.id like '%'||b1.id||'%'; 得到的结果为+--------+----+
| id     | id |
+--------+----+
| 张三千 | 三 |
| 张三千 | 五 |
| 张三千 | 四 |
| 李四万 | 三 |
| 李四万 | 五 |
| 李四万 | 四 |
| 王五   | 三 |
| 王五   | 五 |
| 王五   | 四 |
| 茅十八 | 三 |
| 茅十八 | 五 |
| 茅十八 | 四 |
| 马六   | 三 |
| 马六   | 五 |
| 马六   | 四 |
+--------+----+貌似a1.id,b1.id两个字段并没有进行匹配。我想请教的是:(1)我该怎么办? (2)如果不用like
,还有更好的方法不?谢谢!

解决方案 »

  1.   

    方法很多,下面你可以通过join ,exist, where 和不同的表达式 instr, like , regexp等找出很多种写法。
    ||在MySQL中一般情况下是做OR运算,而不是标准SQL中的字符串加。mysql> select * from a1 where exists (select id from b1 where INSTR(a1.id,id));
    +--------+
    | id     |
    +--------+
    | 张三千 |
    | 李四万 |
    | 王五   |
    +--------+
    3 rows in set (0.08 sec)mysql>mysql> select * from a1 where exists (select id from b1 where a1.id like concat(
    '%',id,'%'));
    +--------+
    | id     |
    +--------+
    | 张三千 |
    | 李四万 |
    | 王五   |
    +--------+
    3 rows in set (0.06 sec)mysql>mysql> select * from a1 where exists (select id from b1 where a1.id regexp id);
    +--------+
    | id     |
    +--------+
    | 张三千 |
    | 李四万 |
    | 王五   |
    +--------+
    3 rows in set (0.05 sec)mysql>mysql> select distinct a1.id
        -> from a1 inner join  b1 on a1.id regexp b1.id;
    +--------+
    | id     |
    +--------+
    | 张三千 |
    | 李四万 |
    | 王五   |
    +--------+
    3 rows in set (0.01 sec)mysql>mysql> select distinct a1.id
        -> from a1 , b1
        -> where INSTR(a1.id,b1.id);
    +--------+
    | id     |
    +--------+
    | 张三千 |
    | 李四万 |
    | 王五   |
    +--------+
    3 rows in set (0.02 sec)mysql>
      

  2.   

    当您的问题得到解答后请及时结贴.
    http://topic.csdn.net/u/20090501/15/7548d251-aec2-4975-a9bf-ca09a5551ba5.html