Is this a valid correlated sub query with joins?

折月煮酒 提交于 2019-12-20 06:14:02

问题


So I have a table Car(Car_id, Value, Make), another table Person(Person_id, Name) and a third table linking the two together PerCar(Car_id, Person_id).

So I have this correlated subquery:

SELECT MAKE, VALUE 
FROM CAR WHERE VALUE > (SELECT AVG(VALUE) FROM CAR C WHERE C.CAR_ID = CAR_ID);

So if I wanted to display the person's name also, is this also valid correlated sub query:

SELECT Car.Make, Car.Value, Person.Name 
FROM PerCar NATURAL JOIN Car 
NATURAL JOIN Person where Car.Value > (SELECT AVG(VALUE) FROM Car);

回答1:


Your query should be as below-

You can check DEMO HERE

SELECT Car.Make, 
Car.Value, 
Person.Name 
from Car
INNER JOIN CarPer 
    ON Car.Car_id = CarPer.Car_id 
INNER JOIN Person
    ON Person.Person_id = CarPer.Person_ID        
WHERE Car.Value > (SELECT AVG(VALUE) FROM Car);

Remember, here joining can be INNER, OUTER, LEFT or other joins based on your requirement and data structure.




回答2:


This is NOT a correlated subquery:

SELECT MAKE, VALUE 
FROM CAR
WHERE VALUE > (SELECT AVG(VALUE) FROM CAR C WHERE C.CAR_ID = CAR_ID);

Always qualify all column references in a query.

You think the WHERE clause is:

WHERE CAR.VALUE > (SELECT AVG(VALUE) FROM CAR C WHERE C.CAR_ID = CAR.CAR_ID);

But it is really:

WHERE CAR.VALUE > (SELECT AVG(C.VALUE) FROM CAR C WHERE C.CAR_ID = C.CAR_ID);

There is no reference to the outer query, so this is not correlated. I would write this as:

SELECT C.MAKE, C.VALUE 
FROM CAR C
WHERE C.VALUE > (SELECT AVG(C2.VALUE) FROM CAR C2 WHERE C2.CAR_ID = C2.CAR_ID);

However, it is unlikely that this will return any rows. Given your lack of problem statement and the values in your tables, a sensible query would return "all cars whose value is higher than the average for their make"

SELECT C.MAKE, C.VALUE 
FROM CAR C
WHERE C.VALUE > (SELECT AVG(C2.VALUE) FROM CAR C2 WHERE C2.MAKE = C.MAKE);

Because the rest of your question is predicated on the first query being a "correlated subquery", the rest of the question does not make sense.



来源:https://stackoverflow.com/questions/59124475/is-this-a-valid-correlated-sub-query-with-joins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!