mardi 6 octobre 2015

Why does this SQL work? (I don't think it should!)

Some time ago, using SQLite, I wrote a pretty large bit of SQL as the basis of a view. Now I look at again I cannot see how it could possibly work, but its been working fine for ages. The gist of the sql is below. I get the correct value of average(Result) in both x and y even though x uses the clause...

select avg(result) from TableB

...when tableB doesn't contain a field called result.

Why doesn't this code fail?

CREATE TABLE TableB 
( TheKey TEXT);

 CREATE TABLE TableA 
 (  TheID TEXT,
  TheKey TEXT,
  result INTEGER  );

SELECT
    TheID,
    avg(result) as y,
    (select avg(result) from TableB as T where T.TheKey = TableA.TheKey) as x,
FROM 
    TableA
LEFT JOIN   
    TableB  
ON TableA.TheKey = TableB.TheKey
GROUP BY 
    TheID, TableA.TheKey

Aucun commentaire:

Enregistrer un commentaire