表table1  
id,name1
100,刘
101, 李表table2
id , name2
100, 班长
v_id  其它职务现在我需要查询的结果是id, name2
                      100, 班长
                      v_id 其它职务就是说将表table1的id和table2的id相关联查询,然后还要包括table2.id like 'v_%';
我是这样写的
select table2.id,table2.name2 from table1,table2 where table2.id = table1.id or table2.id like 'v_%';
可是最后查出来的结果是
100, 班长
v_id 其它职务
v_id 其它职务
请问v_id为什么出现了两次啊,我加上distinct也是不行啊
谢谢

解决方案 »

  1.   

    select * from (select * from table1 union select * from table2) a
    where a.id like 'v_%';
      

  2.   

    select table2.id,table2.name2 from table1,table2 where table2.id = table1.id 
    union distinct select table2.id,table2.name2 from table1,table2 where table2.id like 'v_%';
    这样可以么?
      

  3.   

    select distinct table2.id,table2.name2 from table1,table2 where table2.id = table1.id or table2.id like 'v_%';
    就可以啦.
    你的TABLE1有多少条记录,v_id 其它职务就重复出现多少次.
      

  4.   

    select table2.id,table2.name2 from table1,table2 where table2.id = table1.id 
    union 
    select table2.id,table2.name2 from table1,table2 where table2.id like 'v_%';
    也行
      

  5.   

    怎么可能不行?
    select table2.id,table2.name2 from table1,table2 where table2.id = table1.id 
    union 
    select table2.id,table2.name2 from table2 where table2.id like 'v?_%' escape '?';
    是不是要写成这样?
    如果这还不符合你的要求的话那就没话说了.还有就是用DISTINCT 就完全可以的.你说不行的话就是你自己用错了.
      

  6.   

    我的意思是这样的,table1,table2两个表,其中使用ID进行关联
    将id相同的记录提出来,然后在table2中有一些比较特殊的id,是以V_开头的,这样的记录我也要提取出来,请问这样功能的sql该怎么写
    谢谢
      

  7.   

    sbaz(万神渡劫)的方法是正确的,符合楼主的意思的啊: 
    select table2.id,table2.name2 from table1,table2 where table2.id = table1.id 
    union 
    select table2.id,table2.name2 from table2 where table2.id like 'v?_%' escape '?';
    table1,table2两个表,其中使用ID进行关联,得到id相同的记录集,合并在table2中有一些比较特殊的id,是以V_开头的记录集(不包含重复记录)
    应该是没有问题的,楼主试试看再说