在前面的帖子有问过这个问题。
上一个帖子。http://topic.csdn.net/u/20090122/11/6b95a73f-f36d-4690-9872-e359434659ba.html在前面的问题中的table2表中增加一个TypeId字段,我要查询表中名称相同,并且名称相同数据大于2条,并且TypeId为某个值的所有数据,如何写SQL? 例如 
table_11
Id      Name
1 新话题
2 新话题
3 新话题
4 字符串
5 问题
6 问题
7 写法 table_12
Id  table1Id  typeId
1 1 3
2 2 3
3 4 3
4 5 1
5 6 1
6 7 1
7 4 3
8 4 3
9 1 3
10 2 6
11 3 8
12 1 0 使用下面的SQL
select a.*,b.* 
from table_11 a,table_12 b
where exists
(
select *
from table_11
where [name]=a.[name]  
group by [name]
having count(*) > 1
) and a.ID=b.tableID
order by a.name
查询出的将是整个表中名称相同并且大于2的所有数据。但我想增加typeId为某值时,结果就不对了。例如typeid = 0,这时将 and a.ID=b.tableID 改为 and a.ID=b.tableID typeid = 0 查询出的将是对于整个表来讲名称重复,然后typeid = 0。并不是先约束typeid = 0的所有数据中名称重复。
如何修改?

解决方案 »

  1.   

    select a.*,b.* 
    from table_11 a,table_12 b 
    where b.typeid = 0 and exists 

    select * 
    from table_11 
    where [name]=a.[name]  
    group by [name] 
    having count(*) > 1 
    ) and a.ID=b.tableID and b.typeid = 0
    order by a.name 
      

  2.   

    我的意思是前面我给的SQL查询出的是连接table_11 ,table_12 2张表后的查询出所有名称重复的数据。然后再根据typeid来查询typdid为某值时结果就不对了。因为没有先约束typdid,而是查询出整张表的名称重复后在查询typid为某值。而不是先约束typdid后的数据中名称重复的。我做了一下下修改,好像没问题了,但是逻辑感觉太乱了,麻烦看看。select a.*,b.* 
    from table_11 a,table_12 b
    where exists
    (
    select *
    from (select table_11.* from table_11, table_12 where  table_11.ID=table_12.tableID and table_12.tyepid = 3) as c
    where c.[name]=a.[name]
    group by c.[name]
    having count(*) > 1
    ) and a.ID=b.tableID and tyepid = 3
    order by a.name