如何在主选择查询中打印嵌套查询的值?

时间:2014-04-11 08:50:24

标签: mysql sql oracle oracle11g

我有3张桌子。一个是旅行表,并且连接到许可证号码表,该表连接到表雇员。我的内心选择是:

SELECT  TR.L#, TR.REG# , COUNT(TR.REG#)
FROM TRIP TR
GROUP BY TR.L#, TR.REG#

给我许可证编号和卡车登记号码以及每辆卡车的许可证的行程次数。现在我需要添加另一个表中的许可证号的信息。如何将这三列传输到主选择并将其打印在员工姓名旁边?

   SELECT  E.FNAME, E.LNAME
    FROM EMPLOYEE E
    WHERE E.E# IN (
            SELECT E#
            FROM DRIVER
            WHERE L# IN (
                        SELECT  TR.L#, TR.REG# , COUNT(TR.REG#)
                         FROM TRIP TR
                    GROUP BY TR.L#, TR.REG#
            )
    );

错误:

太多的值

尝试加入:

SELECT   TR.L#, TR.REG# , COUNT(TR.REG#), D.E#  
FROM TRIP TR
INNER JOIN DRIVER D ON D.L# = TR.L#
GROUP BY TR.L#, TR.REG#

2 个答案:

答案 0 :(得分:2)

我认为编写查询最简单,以便连接的顺序与关系匹配,就好像数据从行程中的驱动器流向员工一样,沿着这些方向:

select tr.l#, tr.reg#, d.e#, count(1) trips
from trip tr
join driver d on (d.l# = tr.l#)
join employee e on (e.e# = d.e#)
group by tr.l#, tr.reg#, d.e#

答案 1 :(得分:0)

SELECT  E.FNAME, E.LNAME, sub.<DRIVER FIELD NAME>
FROM EMPLOYEE E JOIN (
            SELECT *
            FROM DRIVER
            WHERE L# IN (
                        SELECT  TR.L#, TR.REG# , COUNT(TR.REG#)
                         FROM TRIP TR
                    GROUP BY TR.L#, TR.REG#
            ) 
    ) sub ON E.E#=sub.E#