SQL嵌套查询搜索多个字段

时间:2017-01-17 11:59:48

标签: sql vb.net

任何人都可以帮助我在VB表单中使用的嵌套查询,因为我正在努力。

所以查询的第一部分如下。

select 
    [incidentid] as incidentid, 
    ('Incident' &' '&[incidentID] &' '&'has a new containment') as incisearch 
from 
    containment 
where 
    transtime > @logout

这样可以正常工作,并会返回正确的信息。我想要做的是搜索另一个参数@username

此信息保存在名为incident的表格中,可在@usernameincidentownerpurchasingmember字段中找到additionalmember参数。< / p>

基本上我希望查询返回结果,如果在incidentownerpurchasingmemberadditionalmember上次登录的用户之后输入了包含。

所以这是我到目前为止所尝试的:

select 
    [incidentid] as incidentid, 
    ('Incident' &' '&[incidentID] &' '&'has a new containment') as incisearch 
from 
    containment 
where 
    transtime > @logout and 
    purchasingmember in 
       (select 
            [incidentid] 
        from 
            incident 
        where 
            purchasingmember = @username)

我首先想到的是,我只是通过搜索一个字段而不是几个字段来尝试它,这会返回错误

  

没有给出一个或多个必需参数的值。

然后我还尝试使用以下

一次搜索多个字段
select 
    [incidentid] as incidentid, 
    ('Incident' &' '&[incidentID] &' '&'has a new containment') as incisearch 
from 
    containment 
where 
    transtime > @logout and 
    @username in 
       (select 
            [incidentid] 
        from 
            incident 
        where 
            (incidentowner = @username) or 
            (purchasingmember = @username) or 
            (additionalmember = @username))

此查询不会失败,但它不会返回任何结果,我希望只返回一个。所以这个查询没有被破坏我只是不认为我已经告诉它要正确搜索什么。有人可以帮忙吗?

从收到以下评论后,我还修改了以下代码,但仍未按预期工作

select 
    [incidentid] as incidentid, 
    ('Incident' &' '&[incidentID] &' '&'has a new containment') as incisearch 
from 
    containment 
where 
    transtime > @logout and 
    incidentid in 
       (select 
            [incidentid] 
        from 
            incident 
        where 
            (incidentowner = @username) or 
            (purchasingmember = @username) or 
            (additionalmember = @username))

1 个答案:

答案 0 :(得分:0)

感谢@ Jinx88909我设法解决了这个问题,正确的SQL命令应该是

select 
     containment.incidentid as incidentid, 
     ('Incident' &' '& containment.incidentID &' '&'has a new containment') as incisearch 
from 
     (containment INNER JOIN incident ON containment.incidentid = incident.incidentid) 
where 
     containment.transtime > @logout and 
     (incident.incidentowner = @username or incident.purchasingmember = @username or incident.additionalmember = @username)