SQL join statement with where clause

五迷三道 提交于 2019-12-08 11:08:40

问题


I have this question, from I am trying to get through. I have been trying to do this for hours, it would be really great if someone could point us in the right direction.

This is in german so I am going to translate it in English:

We only have problem with part (d)

(d) Write an SQL statement that gives names of the restaurant and Ort(Place) of the restaurant that do not order any Salat.

The expected result would be:

Da Mafia : Göttingen
Venezia : Kassel


回答1:


You can try like this:

  SELECT name,ort FROM kunde WHERE name NOT IN (SELECT DISTINCT(pizzeria) FROM Liefervertrag WHERE product='salat')



回答2:


It doesn't apply to LolCoder's answer, but remember to be careful with NOT IN when the subquery has nulls.

This is another approach with variations on the theme. It's not exactly fancy even though it does use an inner join. You'll probably find them all in the wild.

My preference is the first one. I'm also usually explicit about "else null" even though isn't technically necessary.

-- A
SELECT name, min(ort) as ort
FROM kunde as k INNER JOIN Liefervertrag as l on l.pizzeria = k.name
GROUP by name
HAVING count(case when l.product = 'salat' then 1 else null end) = 0

-- B
SELECT name, min(ort) as ort
FROM kunde as k INNER JOIN Liefervertrag as l on l.pizzeria = k.name
GROUP by name
HAVING sum(case when l.product = 'salat' then 1 else 0 end) = 0

-- C
SELECT name, ort
FROM kunde as k INNER JOIN Liefervertrag as l on l.pizzeria = k.name
GROUP by name, ort
HAVING count(case when l.product = 'salat' then 1 else null end) = 0

-- D
SELECT name, ort
FROM kunde as k INNER JOIN Liefervertrag as l on l.pizzeria = k.name
GROUP by name, ort
HAVING sum(case when l.product = 'salat' then 1 else 0 end) = 0


来源:https://stackoverflow.com/questions/11377425/sql-join-statement-with-where-clause

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