Domanda

I have a task to write a query that uses a single inner join and cross join(s). The query I have already written that should return the same result looks like this :

SELECT T.PRICE, S.ROW, S.NUMBER, M.TITLE  
FROM 
[cinema_no_keys].[dbo].[TICKET] T cross join 
[cinema_no_keys].[dbo].[MOVIE] M cross join 
[cinema_no_keys].[dbo].[SEAT] S cross join 
[cinema_no_keys].[dbo].[SHOW] SH
WHERE
T.ID_SEAT = S.ID_SEAT AND
M.ID_MOVIE = SH.ID_MOVIE AND
SH.DATE_HOUR = T.DATE_HOUR
È stato utile?

Soluzione

cross join is a special case of inner join: it is an inner join without any conditions. In other words, it joins every row of the table. The only reason it exists is so that you don't have to write a silly statement like inner join TABLE on 1=1.

You should only use cross join when you want to join every single row. It makes no sense to use it and then have conditions in the where clause specifying which rows should match (as you are doing).

The proper way to do it is use inner join, and specify the join conditions in the on clause rather than the where clause. This gives your query more of a logical flow, and in many cases it will also be more efficient (the earlier you exclude rows from your result, the faster your query runs).

Here is a revised query that uses inner join:

select T.PRICE, S.ROW, S.NUMBER, M.TITLE  
    from [cinema_no_keys].[dbo].[TICKET] T 
    inner join [cinema_no_keys].[dbo].[SEAT] S on
        T.ID_SEAT = S.ID_SEAT
    inner join [cinema_no_keys].[dbo].[SHOW] SH on
        SH.DATE_HOUR = T.DATE_HOUR
    inner join [cinema_no_keys].[dbo].[MOVIE] M on
        M.ID_MOVIE = SH.ID_MOVIE

I changed the order of joins: because movie links to a field in show, show should come before movie.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top