2009-11-27 179 views
0

我有3个表格,如下所示。简单的sql查询

salesman(sid,sname) 
location(lid,lname) 
sales_loc(sid,lid) 

现在我想打印的SID和谁曾经访问过的所有位置推销员的SNAME。 我想要一个SQL查询,我不想要一个PL/SQL代码。

+2

我正要猜测作业。但是,家庭作业很少涉及像Oracle这样的软件...... – Joey 2009-11-27 08:23:00

+0

好吧,现在有一个Express版本;) – MartW 2009-11-27 08:24:44

+0

也许某些东西在我头脑上传开了“whoosh”,但我很难理解你在问什么。这两个表如何链接? – Greg 2009-11-27 08:24:46

回答

7
select sid, sname from salesman 
where not exists 
     (select 1 from location 
      where not exists 
        (select 1 from sales_loc 
        where sid=saleman.sid 
        and lid = location.lid)); 
+0

Oookay,这是一个有趣的一。从来没有真正想过你可以否定这个陈述;不错。 – Joey 2009-11-27 08:26:41

+0

是的,我仍然试图围绕它:) – cflewis 2009-11-27 08:34:49

+1

Lewisham:我到处都没有地方,我没有去过。 – 2009-11-27 09:01:57

4

的另一种方法:

select sid, sname from salesman 
where 
    (select count(*) from location) = 
    (select count(*) from sales_loc where sales_loc.sid = salesman.sid) 

编辑: 万一sales_loc(sid,lid)对不是一个键时,下面的查询是比较合适的,
如ammoQ建议:

select sid, sname from salesman 
where 
    (select count(*) from location) = 
    (select count(distinct lid) from sales_loc where sales_loc.sid = salesman.sid) 
+0

人类可读:) – Amarghosh 2009-11-27 08:46:37

+0

* sigh * snap ... =) – Will 2009-11-27 08:46:38

+0

+1,尽管它做出了一些假设;我将第二个子查询设置为“select count(distinct lid)...”,所以当sales_loc中有一个以上的销售员和地址条目时,它仍然有效。 – 2009-11-27 08:47:52

0

获取所有销售员recs访问的地点数等于loca的数量蒸发散。

select sm.* from salesman as sm 
where (select count(sl.*) from sales_loc as sl where sl.sid = sm.sid) 
= (select count(l.*) from location as l); 
0

还有一个锅!

鉴于这些推销员和他们的领土......

SQL> select s.sname, l.lname 
    2 from salesman s 
    3   , location l 
    4   , sales_loc sl 
    5 where sl.sid = s.sid 
    6 and sl.lid = l.lid 
    7 order by s.sid, l.lid 
    8/

SNAME  LNAME 
---------- ---------- 
FOX  TRAIN 
FOX  BOAT 
KNOX  BOAT 
KNOX  HOUSE 
SAM  TRAIN 
SAM  BOAT 
SAM  HOUSE 

7 rows selected. 

SQL> 

...此查询提取谁访问了所有的人的一个...

SQL> select s.sname 
    2 from salesman s 
    3 where s.sid not in (
    4  select sid from (
    5   select cjs.sid, cjl.lid 
    6   from salesman cjs 
    7     cross join location cjl 
    8   minus 
    9   select sl.sid, sl.lid 
10   from sales_loc sl 
11  ) 
12 ) 
13/

SNAME 
------ ---- 
SAM 

SQL> 
+0

在sqlserver中使用此查询的任何人都应该将minus改为except。 – Tebo 2009-11-27 09:35:30

+0

您还应该为第二个select语句附加一个别名。从(...)中选择ss.sid – Tebo 2009-11-27 09:40:48

0

这应该工作。我试过了。

select a.sid, a.salesman, count(a.sid) as total from salesman a 
inner join sales_loc b on b.sid = a.sid 
inner join location c on c.lid = b.lid 
group by a.sid, a.salesman 
having count(a.sid) = (select count(*) from location) 

它使用要比较的位置总数。

0

推销员(SID,SNAME) 位置(盖,L-NAME) sales_loc(SID,盖子)

选择s.sid,从推销员小号s.sname,位置升,sales_loc SL 其中s.sid = sl.sid and l.lid = sl.lid