2

SQLコード、リレーショナル代数、タプルリレーショナル計算の両方で、特定のクエリに行き詰まったテスト試験を行っています。

Branch クエリは次のように述べています。関係にリストされているすべてのタイプのブランチを収容する (都市、州) のペアを見つけます。

どこBranchにある:

Branch_ID (Primary key)
Branch_City
Branch_State
Branch_Type

市区町村は次のとおりです。

City_Name (Primary key)
State_Name (Primary key)
Population

and Branch_Cityandは、それぞれandBranch_Stateの外部キーです。City_NameState_Name

「ルール」は、などの集約関数はCOUNT使用MAXできないというものです。

クエリは、MySQL と PostgreSQL によって「理解」されている必要がありますが、PostgreSQL では利用できるが MySQLEXCEPTではINTERSECT利用できない などの関数を使用できます。

FROM句にサブクエリはありません

前述のように、sQL、リレーショナル代数、およびタプルリレーショナル計算について回答を提供できれば幸いです。それらの質問は私を行き詰まらせました。

前もって感謝します!

4

2 に答える 2

3

私はMySqlやPostGresSQLを持っていないので、これはSQL Serverの構文ですが、アイデアを与えるはずです:

with branches as (
  select * from ( values
    ('Perth',1),
    ('Toronto',1), ('Toronto',2), ('Toronto',3),
    ('Hamilton',2), ('Hamilton',3)
  ) branches(City,  Branch_Type)
)

  select distinct
    City
  from branches
except
  select distinct 
    b.City
  from branches t 
  cross join branches b 
  left join branches b2 on b2.Branch_Type = t.Branch_Type and b2.City = b.City
  where b2.Branch_Type is null

必要なセット操作を示すために、必要最小限に切り詰めました。

クエリの上半分は、3 つの都市すべてを返します。後半はハミルトンとパースのみを返します。クエリ全体でトロントのみが返されるようにします。

私は 30 年間、リレーショナル代数もリレーショナル微積分も使用していませんが、上記のクエリをそれらの方言で表現することは、単なる翻訳作業です。

更新 - MySQL の場合:

with branches as (
  select * from ( values
    ('Perth',1),
    ('Toronto',1), ('Toronto',2), ('Toronto',3),
    ('Hamilton',2), ('Hamilton',3)
  ) branches(City,  Branch_Type)
)

select distinct
  City
from branches
where City not in (
  select distinct 
    b.City
  from branches t 
  cross join branches b 
  left join branches b2 on b2.Branch_Type = t.Branch_Type and b2.City = b.City
  where b2.Branch_Type is null
  )

サブクエリは FROM 句ではなく WHERE 句にあるため、これは正当である必要があります。左結合と表現することもできますが、サブクエリを FROM 句に移動すると思います。

于 2013-03-23T10:35:09.903 に答える
3
-- The query states: Find the (city,state) pairs which house a branch of every type which is listed in the Branch relation.
--                                               ((((                    ^^^^^ ^^^^    ))
-- This is equivalent to: Find cities for which "There does NOT EXIST a branchType that is NOT PRESENT in this City"
-- This leads to the double "NOT EXISTS (NOT EXISTS())" solution to relational devision.::
SELECT  * -- city,state
FROM city c
WHERE NOT EXISTS (
        -- find a branchtype that is not present in our city
        SELECT * FROM Branch b
        WHERE NOT EXISTS (
                -- same city for this  branchtype
                SELECT * FROM Branch nx
                WHERE nx.Branch_City = c.City_Name AND nx.Branch_State = c.State_Name
                AND nx.Branch_Type = b.Branch_Type
                )
        )
        ;

関係分割は、このタイプの操作の用語です。

ところで:テーブルの複合(都市、州)主キーは、cityあなたを混乱させるためだけにあります。通常、数値 (サロゲート)city_idを都市テーブルの主キーとして使用し、それをテーブルの外部キーとしても使用しbranchesます。

于 2013-03-23T13:06:44.220 に答える