从SQL Server检索特定数据存储过程

时间:2015-12-10 05:29:25

标签: sql-server

我正在使用的两个表是

Contacts (Contact_id, Contact_name,...)
Contacts_group_options (Contact_id, Group_id, Status)

我希望从Contacts_group_options表中获取不属于特定组的所有联系人。 问题是,如果第一个表有Contact_id s 1,2,3,4,第二个表有Contact_id s 2,3对于Group_id = 1,我希望结果为1和4。但我得到1,3,4,1,2,4。

首先将1与2进行比较。两者不相同。输出1,然后2,2相同,所以不输出,3输出2输出4,输出4输出4,1输出1,2输出3输出2,3输出3输出4输出4输出4 。 存储过程是:

Select 
    m.Contact_id,
    m.Contact_code,
    m.Contact_name,
    m.Phone_number,
    m.Mail_id,
    m.Designation,
    m.Department,
    m.User_id,
    m.User_type,
    m.Status
from 
    Contacts as m,
    Contact_group_options as b
    ,@tblType_contacts2group as i
where
    b.Group_id = i.Group_id
    and m.Contact_id != b.Contact_id

3 个答案:

答案 0 :(得分:0)

我认为你可以用一个简单的NOT EXISTS

来做到这一点
SELECT c.*
FROM Contacts AS c
WHERE 
    NOT EXISTS(
        SELECT 1 
        FROM Contact_group_options
        WHERE
            Group_id = 1
            AND Contact_id = c.Contact_id
    )

答案 1 :(得分:0)

你可以试试这个:

-- NOT EXISTS
SELECT C.*
FROM Contacts C
WHERE NOT EXISTS (SELECT 1 FROM Contacts_group_options WHERE Group_id = 1 AND C.Contact_id)

-- NOT IN
SELECT *
FROM Contacts
WHERE Contact_id NOT IN (SELECT Contact_id FROM Contacts_group_options WHERE Group_id = 1)

答案 2 :(得分:0)

您的结果集包含很多行,因为您实际上有三个表:Contacts,Contact_group_options和@ tblType_contacts2group。

也许你想写这样的东西:

with caselist (
  select worker1 as worker from cases union all
  select worker2 as worker from cases union all
  select worker3 as worker from cases
)
select companyname, count(*)
from company c
inner join workers w on c.companyid = w.companyid
inner join caselist cl on w.workerid = cl.worker
group by companyname

注意:由于在您的示例中未明确定义@ tblType_contacts2group,因此上述查询可能无法获得正确的结果。

正如Felix所提到的,你应该总是使用正确的连接。例如。上面的查询可能是这样的:

-- compacted for to make it more readable
Select 
    m.Contact_id, m.Contact_code, m.Contact_name, m.Phone_number,
    m.Mail_id, m.Designation, m.Department, m.User_id, m.User_type, m.Status
from Contacts as m
where not exists (select 1 from @tblType_contacts2group as i where i.Group_id = m.Group_id)

但是,请记住,通常,使用IS NULL的LEFT JOIN比NOT EXISTS等效的慢。