简体   繁体   中英

With a CTE, how do I select the rows from tableB even when tableA returns no results?

I have the following sqlfiddle: http://sqlfiddle.com/#!15/e971e/10/0

So, I am running the query against two tables simultaneously. I'd like to get all info for "fran" even if she isn't in 1 table or the other. I have:

WITH tableA AS(
  SELECT id, name, age 
  FROM a WHERE name = 'fran'
),
tableB AS(
  SELECT id, name, address 
  FROM b WHERE name = 'fran'
)

SELECT tableA.id, tableA.name, tableA.age, tableB.address
FROM tableA, tableB

/*
WITH tableB AS(
  SELECT id, name, address 
  FROM b WHERE name = 'fran'
)

SELECT tableB.address FROM tableB
*/

This returns no rows even though she is in tableB (run the commented portion and it returns her address).

In the end I'd like something like:

id  name    age    address

--   --      --      2 Main

I see your problem Marissa. The thing is that you are not joining the tables.

    WITH tableA AS(
      SELECT id, name, age 
      FROM a WHERE name = 'fran'
    ),
    tableB AS(
      SELECT id, name, address 
      FROM b WHERE name = 'fran'
    )

    SELECT a.id, a.name, a.age, b.address
    FROM tableA a
    FULL OUTER JOIN tableB b
    ON a.id = b.id

This will return you a row only with the address of Fran. The other attributes will be blank because you don't have the data in table A.

Use union all !

WITH tableA AS (
      SELECT id, name, age 
      FROM a
      WHERE name = 'fran'
     ),
     tableB AS (
      SELECT id, name, address 
      FROM b
      WHERE name = 'fran'
     )
select 'a' as which, a.*
from tableA a
union all
select 'b' as which, b.*
from tableB b;

The join solutions will multiply the number of rows in the table. So, if a has 3 rows and b has 4 rows, then the result set will have 12 rows. With this method, the result set will have 7 rows.

You need a Full Join plus Coalesce:

WITH tableA AS(
  SELECT id, name, age 
  FROM a WHERE name = 'fran'
),
tableB AS(
  SELECT id, name, address 
  FROM b WHERE name = 'fran'
)

SELECT COALESCE(tableA.id, tableB.id) AS id
   ,COALESCE(tableA.name, tableB.name) as name
   ,tableA.age, tableB.address
FROM tableA FULL JOIN tableB
ON tableA.id = tableB.id

You need a full outer join.

Based on your sqlfiddle the id is not suitable for joining (id 2 is fred in table A and fran in table B), you need to use the name column instead. You should ensure that name is indexed for proper performance.

SELECT
  a.id, a.name, a.age,
  b.id, b.name, b.address
FROM a
FULL OUTER JOIN b ON b.name = a.name
WHERE a.name = 'fran' or b.name = 'fran'

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