如何从与另一个表中的所有值匹配的表中获取记录

时间:2019-07-04 10:03:45

标签: sql oracle relational-division

如何编写查询来获取驱动所有可用总线的所有驱动程序?

桌车

--------
BUS_ID
--------
1
2
3
4

表驱动程序

-----------------------
BUS_ID  |   DRIVER_NAME
-----------------------
1   |   John
2   |   John
1   |   Max
2   |   Max
3   |   Max
4   |   Max
2   |   Bill
3   |   Ron
4   |   Ron
1   |   Ron
2   |   Ron

在此示例中,它应返回

DRIVER_NAME
-----------
Max
Ron

注意:请勿对查询中的任何值进行硬编码。

我写了以下内容

SELECT DRIVER.DRIVER_NAME
FROM   DRIVER
WHERE  BUS_ID = ALL( SELECT BUS_ID FROM BUS);

3 个答案:

答案 0 :(得分:1)

加入表,按d.driver_name分组,然后将条件放在hading子句中:

select 
  d.driver_name
from bus b inner join driver d
on d.bus_id = b.bus_id
group by d.driver_name
having count(*) = (select count(*) from bus)

答案 1 :(得分:1)

groupinghaving子句一起使用:

SELECT D.DRIVER_NAME
  FROM DRIVER D
 GROUP BY D.DRIVER_NAME
HAVING COUNT(*) = (SELECT COUNT(*) FROM BUS);

DRIVER_NAME
-----------
Ron
Max

Demo

答案 2 :(得分:0)

尝试一下:

SELECT DISTINCT DRIVER_NAME FROM
(SELECT D.DRIVER_NAME, 
COUNT(DISTINCT BUS_ID) OVER (PARTITION BY D.DRIVER_NAME) INDVDL,
COUNT(DISTINCT BUS_ID) OVER () TOTAL
  FROM DRIVER D)
 WHERE INDVDL = TOTAL

-更新-

SELECT DISTINCT
    DRIVER_NAME
FROM
    (
        SELECT
            D.DRIVER_NAME,
            COUNT(DISTINCT BUS_ID) OVER(
                PARTITION BY D.DRIVER_NAME
            ) INDVDL,
            B.TOTAL   AS TOTAL
        FROM
            DRIVER D JOIN
            (
                SELECT
                    COUNT(1) AS TOTAL
                FROM
                    BUS
            ) B ON (1=1)
    )
WHERE
    INDVDL = TOTAL;

干杯!