查询的关系代数表达式

时间:2014-10-10 02:41:23

标签: sql algebra relational relational-algebra

我刚接触关系代数可能是学习SQL查询之前的一个步骤。你能帮我用下面的每个查询使用BASIC OPERATORS来表达关系代数表达式。 这些是包含在总线驱动程序数据库中的表。

•   driver( driver_id, driver_name, age, rating );
•   bus( bus_id, bus_name, color);
•   reserves( driver_id, bus_id, date);
  1. 找到Mark保留的巴士颜色。
  2. 查找评级为至少为7或已预留公交112的司机的所有ID。
  3. 找到未预约黄色巴士的司机的名字。
  4. 查找未预订蓝色公共汽车的年龄超过35岁的司机的身份证明。
  5. 使用基本操作符

    如果有人可以帮助我,我将不胜感激

2 个答案:

答案 0 :(得分:0)

这是我的最终代码。我在网上搜索过,但关系代数是一个相当棘手的主题,所以我只是提出了第一个问题。通过研究完成其余的工作。古德勒克!

我从维基百科得到了(⋈)符号。它被称为自然加入 这里使用的其他符号是希腊字母pi和delta pi用于列名。你知道它是否是列名(属性),如果它在SELECT子句之后 三角洲是条件。如果它在WHERE子句之后,你知道它是否是条件 ⋈用于表名。你知道它是否是表名(关系),如果它在FROM和JOIN子句之后。

1)
SELECT b.COLOR
FROM RESERVES r
NATURAL JOIN BUS b
NATURAL JOIN DRIVER d
WHERE d.DRIVER_NAME='Mark';

Relation = ∏COLOR σDRIVER_NAME='Mark' (RESERVES ⋈ BUS ⋈ DRIVER)

2)
SELECT d.DRIVER_ID
FROM DRIVER d
LEFT JOIN RESERVES r
ON r.DRIVER_ID=d.DRIVER_ID
WHERE d.RATING>=7
OR r.BUS_ID=112;

3)
--Long Method
SELECT d.DRIVER_NAME
FROM DRIVER d
WHERE d.DRIVER_ID NOT IN (
    SELECT r.DRIVER_ID
    FROM BUS b
    JOIN RESERVES r
    ON r.BUS_ID=b.BUS_ID
    WHERE b.COLOR='yellow'
);

--Short Method, use this
SELECT d.DRIVER_NAME
FROM DRIVER d
WHERE NOT EXIST (
    SELECT r.DRIVER_ID
    FROM BUS b
    JOIN RESERVES r
    ON r.BUS_ID=b.BUS_ID
    WHERE b.COLOR='yellow'
    AND r.DRIVER_ID=d.DRIVER_ID
);

4)
--Long Method
SELECT d.DRIVER_ID
FROM DRIVER d
WHERE d.AGE>35
AND d.DRIVER_ID NOT IN (
    SELECT r.DRIVER_ID
    FROM BUS b
    JOIN RESERVES r
    ON r.BUS_ID=b.BUS_ID
    WHERE b.COLOR='blue'
);

--Short Method, use this
SELECT d.DRIVER_ID
FROM DRIVER d
WHERE d.AGE>35
AND NOT EXIST (
    SELECT r.DRIVER_ID
    FROM BUS b
    JOIN RESERVES r
    ON r.BUS_ID=b.BUS_ID
    WHERE b.COLOR='blue'
    AND r.DRIVER_ID=d.DRIVER_ID
);

答案 1 :(得分:0)

有多种方法可以编写这些查询,但这里有一些选项。

(1)您需要跨三个表加入并按名称过滤:

select b.color
from bus b
join reserves r
on b.bus_id = r.bus_id join
join driver d
on d.driver_id = r.driver_id
where d.driver_name = 'Mark'

(或者可以在连接中包含d.driver_name ='Mark')

(2)你需要在两个表之间进行左连接并按bus_id和等级进行过滤:

select d.driver_id
from driver d
left join reserves r
on d.driver_id = r.driver_id
where r.bus_id = 112
or d.rating >= 7

(或者可以结合两个查询)

(3)您需要获取不在加入中的驱动程序:

select d.driver_name
from driver d
where not exists (
    select 1 from reserves r
    join bus b
    on r.bus_id = b.bus_id
    where b.color = 'yellow'
    and r.driver_id = d.driver_id )

(4)与上一篇相似:

select d.driver_id
from driver d
where d.age > 35
and not exists (
    select 1 from reserves r
    join bus b
    on r.bus_id = b.bus_id
    where b.color = 'blue'
    and r.driver_id = d.driver_id )