0

我剛剛學習如何將sql查詢轉換爲關係代數和其他方式。將SQL轉換爲關係代數

Customer(customer_name, customer_street, customer_city) 
Loan(loan_number, branch_name, amount) 
Borrower(customer_name, loan_number) 
Account(account_number, branch_name, balance) 
Depositor(customer_name, account_number) 

我想找到住在費爾法克斯的客戶,有貸款但沒有銀行賬戶。

CustomersInFFX = PROJECT customer_name (SELECT customer_city = 'Fairfax'(Customer)) 
LoanOwners = (CustomersInFFX NATURAL JOIN Borrower NATURAL JOIN Loan) 
AccountHolders = (Depositor NATURAL JOIN ACCOUNT) 
PROJECT customer_name (LoanOwners - AccountHolders) 

這是否有意義?

*選擇:σ,項目名稱:π,自然連接:⋈

+0

對我沒有多大意義..你想問些更具體的思考嗎?我沒有看到任何SQL被翻譯爲或來自,即使我不知道任何有關關係代數,我不認爲'customer_name ='費爾法克斯'會找到你住在那裏的客戶.. – Aprillion 2012-03-28 18:41:55

+0

選擇(σ)正確使用。你不需要看到sql查詢來找出合理的代數。從描述 – 2012-03-28 18:45:05

+0

應該很明顯,哈哈我的意思是customer_city。我的錯... – 2012-03-28 19:04:42

回答

0

下面是使用標準的SQL我的嘗試:

WITH CustomersInFFX 
    AS 
    (
     SELECT * 
     FROM Customer 
     WHERE customer_city = 'Fairfax' 
    ), 
    LoanOwners 
    AS 
    (
     SELECT * 
     FROM CustomersInFFX 
      NATURAL JOIN Borrower 
      NATURAL JOIN Loan 
    ), 
    AccountHolders 
    AS 
    (
     SELECT * 
     FROM Depositor 
      NATURAL JOIN ACCOUNT 
    ) 
SELECT * 
    FROM LoanOwners 
EXCEPT CORRESPONDING DISTINCT 
SELECT * 
    FROM AccountHolders; 

但是,如果LoanOwnersAccountHolders表具有相同的這隻會工作每個具有相同名稱的屬性數量。這不太可能是這種情況,因此您需要投影(SELECT)僅需要的屬性,例如

SELECT customer_name 
    FROM LoanOwners 
EXCEPT DISTINCT 
SELECT customer_name 
    FROM AccountHolders;