使用join解决查询?

时间:2015-11-26 14:13:07

标签: sql oracle sql-server-2008

我有一个表session1,只需要找到以特定ID登录的新条目。

create table session1(name varchar(16),id integer);

insert into session1 values('anshu',20);
insert into session1 values('rohit',21);
insert into session1 values('anshu',21);
insert into session1 values('sonu',21);
insert into session1 values('payal',22);
insert into session1 values('anshu',22);
insert into session1 values('roch',22);
commit;

对于以id 21登录的所有新用户,无连接的查询将如下:

select name from session1 where name NOT IN(Select name from session1 where id<>21);

输出将是:

rohit
sonu

任何人都可以告诉我如何使用连接来解决它?

5 个答案:

答案 0 :(得分:2)

您只有一张桌子,因此无法加入。

在您当前的查询中,您无需使用子查询。您的查询应该是:

while(mySc.hasNext())

要查找 &#34;我有一个表session1,只需要找到使用特定ID登录的新条目。&#34; 您可以使用此查询:

    public static void main(String[] args) {

        Scanner mySc = new Scanner(System.in);

        while(mySc.hasNext()) {

//If input is an integer, push onto stack.
            if (mySc.hasNextInt()) {
                System.out.println(String.format("myStack.push(%s);", mySc.nextInt()));
            }
//Else if the input is an operator or an undefined input.
            else {
                //Convert input into a string.
                String input = mySc.nextLine();
                System.out.println(String.format("input = %s", input));

                //Read in the char at the start of the string to operator.
//                char operator = input.charAt(0);
//                if (operator == '=') {
//                    //Display result if the user has entered =.
//                }
//            **else if ("CTRL-D entered") {
//                System.exit(0);
//            }**
            }
        }
    }

答案 1 :(得分:2)

select s1.name
from session1 s1
  left join session1 s2 on s1.name = s2.name and s1.id <> s2.id
where s1.id = 21
  and s2.id is null

执行为:

SQL>select *
SQL&from session1 s1
SQL&  left join session1 s2 on s1.name = s2.name and s1.id <> s2.id
SQL&where s1.id = 21
SQL&  and s2.id is null;
name                      id name                      id
================ =========== ================ ===========
rohit                     21 -                          -
sonu                      21 -                          -

                  2 rows found

答案 2 :(得分:0)

试试这个

select a.name 
from session1 a 
    left join session1 b 
    on a.name=b.name 
         and b.id =21 
where b.name is null 

答案 3 :(得分:0)

你不需要做加入,如果面试官告诉你做愚蠢的事情来证明你适合这份工作,你应该找到另一份工作。

您的查询也是错误的

这里有你的否定所以:

SELECT NAME
FROM session1
WHERE NAME NOT IN (
        SELECT NAME
        FROM session1
        WHERE id <> 21
        );

相当于

SELECT NAME
FROM session1
WHERE id = 21;

并且都不会产生你的问题输出

答案 4 :(得分:0)

如果我理解你的意思,你可以这样做:

SELECT S1.name FROM session1 S1 LEFT OUTER JOIN
(SELECT name, id FROM session1 WHERE id = 21) S2
ON S1.id = S2.id
WHERE S2.Id IS NOT NULL