Represent a subquery in relational algebra

前端 未结 3 696
滥情空心
滥情空心 2020-12-31 20:44

How do I represent a subquery in relation algebra? Do I put the new select under the previous select condition?

SELECT number
FROM collection
WHERE number =          


        
3条回答
  •  不知归路
    2020-12-31 21:20

    The answer depends on which operators your algebra comprises. A semi-join operator would be most useful here.

    If the common attribute was named number in both relations then it would be a semi-join followed by projection of number. Assuming a sem-join operator named MATCHING, as per Tutorial D:

    ( collection MATCHING anotherStack ) { number }
    

    As posted, the attribute needs to be renamed first:

    ( collection MATCHING ( anotherStack RENAME { anotherNumber AS number } ) { number }
    

    If Standard SQL's (SQL-92) JOIN can be considered, loosely speaking, a relational operator then it is true that SQL has no no semi-join. However, it has several comparison predicates that may be used to write a semi-join operator e.g. MATCH:

    SELECT number
      FROM collection
     WHERE MATCH (
                  SELECT * 
                    FROM collection
                   WHERE collection.number = anotherNumber.anotherStack
                 );
    

    However, MATCH is not widely supported in real life SQL products, hence why a semi-join is commonly written using IN (subquery) or EXISTS (subquery) (and I suspect that's why you name-checked "subquery" in your question i.e. the term semi-join is not well known among SQL practitioners).


    Another approach would be to use an intersect operator if available.

    Something like (pseudocode):

    ( collection project number ) 
    intersect 
    ( ( anotherStack rename anotherNumber as number ) project number )
    

    In SQL:

    SELECT number
      FROM collection
    INTERSECT
    SELECT anotherNumber
      FROM anotherStack;
    

    This is quite well supported in real life (SQL Server, Oracle, PostgreSQL, etc but notably not MySQL).

提交回复
热议问题