简体   繁体   中英

sql case self join

Using oracle The following is a simple version of my code for a self-joined table. There's no reason for a self-join but I was left with the code and it returned unintended results. I've made the fix in my code but I want to understand what's going on.

I will get a 'yes' or 'no' depending on what aliases table I chose for the field population in the case statement.

The below returns a 'yes' but I don't want to move there if population = 'high'.

I don't understand? I suspect alias b is not being evaluated in the case statement but why?

SELECT a.name, 
    a.continent, 
    a.population, 
    case 
      when b.population = 'high' then 'no'    
      else 'yes' 
    end "move there?"
FROM world a,
world b

The query in your question doesn't specify how world a is supposed to be joined to world b , and as such ALL RECORDS IN a are being joined to ALL RECORDS IN b . This is known as a Cartesian join or a CROSS JOIN , and if you were to use ANSI-style joins it would be coded as:

SELECT a.name, 
       a.continent, 
       a.population, 
       case 
         when b.population = 'high' then 'no'    
         else 'yes' 
       end "move there?"
  FROM world a
  CROSS JOIN world b

This is probably not what was intended. :-)

I suspect that what was wanted was to do an INNER JOIN. Using ANSI-style joins this would be something like

SELECT a.name, 
       a.continent, 
       a.population, 
       case 
         when b.population = 'high' then 'no'    
         else 'yes' 
       end "move there?"
  FROM world a
  INNER JOIN world b
    ON b.name = a.name

or, using the 'implied' join style

SELECT a.name, 
       a.continent, 
       a.population, 
       case 
         when b.population = 'high' then 'no'    
         else 'yes' 
       end "move there?"
  FROM world a,
       world b
  WHERE b.name = a.name

Best of luck.

Explicit Join and ON

SELECT a.name, 
    a.continent, 
    a.population, 
    case 
      when b.population = 'high' then 'no'    
      else 'yes' 
    end "move there?"
FROM world a
  inner join world b
     on b.<col> = a.<col>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM