SQL选择标准

时间:2018-03-16 22:14:13

标签: sql

我有两个表temp_number和temp_port,我想只选择那些只有端口名称为'ip sub'的数字,并希望排除那些具有端口名称或端口名称为'local loop'的数字

    temp_number
    -----------------------------------
    numberid  | name
    -----------------------------------
    1         | abc
    2         | def
    3         | ghi
    -----------------------------------  

    temp_port
    -----------------------------------
    portid    | numberid  | name
    -----------------------------------
    1         | 1         |  local loop
    2         | 1         |  ip sub
    3         | 2         |  local loop
    4         | 3         |  ip sub
    -----------------------------------  



    CREATE TABLE temp_number  
    ( numberid number(10),  --pk
      name varchar2(50));  

     CREATE TABLE temp_port  
    ( portid number(10),     --pk 
      numberid number(10),   --fk
      name varchar2(50));  

    insert into temp_number values(1,'abc');
    insert into temp_port values(1,1,'local loop');
    insert into temp_port values(2,1,'ip sub');
    insert into temp_number values(2,'def');
    insert into temp_port values(3,2,'local loop');
    insert into temp_number values(3,'ghi');
    insert into temp_port values(4,3,'ip sub');

What I tried : 
select n.name, p.name from temp_number n, temp_port paving 
where n.numberid=p.numberid  and p.name not in ('local loop');

    actual result:
    -----------------------------------
    name | Name
    -----------------------------------
    abc  | ip sub
    ghi  | ip sub


    expected result:
    -----------------------------------
    name | Name
    -----------------------------------
    ghi  | ip sub

5 个答案:

答案 0 :(得分:1)

您可能想要使用过滤器NOT EXISTS:

SELECT DISTINCT t.name, p.name
  FROM temp_number t
 INNER JOIN temp_port p
    ON p.numberid = t.numberid
 WHERE NOT EXISTS (SELECT 1
                     FROM temp_port s
                    WHERE s.numberid = t.numberid
                      AND s.name = 'local loop')

这样,如果对于某些号码,至少有一个本地循环'端口,它过滤掉该号码

答案 1 :(得分:1)

尝试此过滤

SELECT DISTINCT t.name, p.name
FROM temp_number t, temp_ports p
Where t.numberid=p.numberid AND t.numberid NOT IN
    (SELECT s.numberid FROM temp_port s WHERE s.name = 'local loop')

答案 2 :(得分:0)

选择那些拥有' ip sub'仅端口名称,没有其他端口名称:

type="submit"

答案 3 :(得分:0)

您可以通过以下方式获取数字:

select numberid
from temp_port
group by numberid
having min(name) = 'ip sub' and min(name) = max(name);

如果你真的想要这个名字,加入这个名字非常简单:

select n.numberid, n.name
from temp_number n join
     temp_port p
     on n.numberid = p.numberid
group by n.numberid, n.name
having min(p.name) = 'ip sub' and min(p.name) = max(p.name);

答案 4 :(得分:0)

我们可以通过使用子查询消除不需要的条目,如下所示。

KEY_WOW64_64KEY