Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Qual è la differenza tra queste due query in quanto ottengono due diversi set di risultati?

Non fa davvero alcuna differenza quando lo fai in INNER JOIN.

Tuttavia, quando usi LEFT o RIGHT JOIN, lo fa fa la differenza se inserisci il filtro aggiuntivo nella clausola JOIN o nella clausola WHERE.

Quando inserisci il filtro nella clausola WHERE, SQL Server esegue prima il join, quindi completamente filtra le righe in cui il filtro non si adatta.
--> questo ridurrà il numero di righe restituite

Quando inserisci il filtro in JOIN, SQL Server esegue il filtraggio durante il join, ma solo sulla tabella in cui hai inserito il filtro.
Ottieni comunque tutte le righe dalle altre tabelle, ma solo quelle hanno i dati dalla tabella filtrata in cui si inserisce il filtro.
--> questo non ridurrà il numero di righe, ma le colonne con i dati della tabella dei filtri saranno vuote in più righe

È difficile da spiegare... per chiarire, ecco un esempio:

Prendi i dati di esempio da Risposta di RedFilter :

CREATE TABLE [dbo].[t1](
    [ID] [int] NULL,
    [StatusID] [int] NULL
) ON [PRIMARY]
CREATE TABLE [dbo].[t2](
    [ID] [int] NULL
) ON [PRIMARY]
INSERT INTO t1 (ID, StatusID) VALUES (1, 10)
INSERT INTO t1 (ID, StatusID) VALUES (2, 11)
INSERT INTO t1 (ID, StatusID) VALUES (3, 12)
INSERT INTO t1 (ID, StatusID) VALUES (4, 12)
INSERT INTO t2 (ID) VALUES (1)
INSERT INTO t2 (ID) VALUES (3)
INSERT INTO t2 (ID) VALUES (5)

...ed esegui le seguenti query su di esso:

/* this returns four rows, but only two will have data 
from the second table in the second column */
SELECT t1.ID, t2.ID
FROM t1 
LEFT JOIN t2 ON t1.Id = t2.Id 

/* this returns only one row: the one where t2.ID = 1 */
SELECT t1.ID, t2.ID
FROM t1 
LEFT JOIN t2 ON t1.Id = t2.Id 
WHERE t2.ID = 1 

/* this returns four rows as in the first query, but only one 
row will have data in the second column: the one where t2.ID = 1 */
SELECT t1.ID, t2.ID
FROM t1 
LEFT JOIN t2 ON t1.Id = t2.Id 
AND t2.ID = 1 

Nota i diversi risultati come indicato nei commenti.