简体   繁体   中英

SQL query not returning rows if empty

I am new to SQL and I would like to get some insights for my problem I am using the following query,

  select id,
         pid 
    from assoc
   where id in (100422, 100414, 100421, 100419, 100423)

All these id need not have pid, some doesn't and some has pid. Currently it skips the records which doesn't have pid. I would like a way which would show the results as below.

         pid    id
         -----------
         703    100422
         313    100414
         465    100421
         null   100419
         null   100423

Any help would be greatly appreciated. Thanks!

Oh, I think I've got the idea: you have to enumerate all the id s and corresponding pid s. If there's no corresponding pid , put null (kind of outer join ). If it's your case, then Oracle solution can be:

   with 
     -- dummy: required ids
     dummy as (
                 select 100422 as id from dual
       union all select 100414 as id from dual
       union all select 100421 as id from dual
       union all select 100419 as id from dual
       union all select 100423 as id from dual),
     -- main: actual data we have
     main as (
       select id,
              pid 
         from assoc
           -- you may put "id in (select d.id from dummy d)"
        where id in (100422, 100414, 100421, 100419, 100423))

   -- we want to print out either existing main.pid or null
   select main.pid as pid,
          dummy.id as id
     from dummy left join main on dummy.id = main.id

id is obtained from other table and assoc only has pid associated with id .

The assoc table seems to be the association table used to implement a many-to-many relationship between two entities in a relational database.

It contains entries only for the entities from one table that are in relationship with entities from the other table. It doesn't contain information about the entities that are not in a relationship and some of the results you want to get come from entities that are not in a relationship.

The solution for your problem is to RIGHT JOIN the table where the column id comes from and put the WHERE condition against the values retrieved from the original table (because it contains the rows you need). The RIGHT JOIN ensures all the matching rows from the right side table are included in the result set, even when they do not have matching rows in the left side table.

Assuming the table where the id column comes from is named table1 , the query you need is:

SELECT assoc.id, assoc.pid 
FROM assoc
    RIGHT JOIN table1 ON assoc.id = table1.id
WHERE table1.id IN (100422, 100414, 100421, 100419, 100423)

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