Question

I have this query that will work if there is data in both tables

SELECT a.location, b.location, a.refno, b.note
FROM (
    SELECT location, refno
    FROM tableA WHERE refno = '1234'
) a, (
    SELECT location, note FROM tableB WHERE note = LN1234567
) b

but some of the time there may not be data in either one of the tables for the specific match in the WHERE clauses

I've also tried this which does work but i need the data on one row

SELECT location, refno
FROM tableA
WHERE refno = '1234'

UNION

SELECT location, note
FROM tableB
WHERE note = 'LN1234567'

My question is, is there an alternative way of querying both tables so I get one row with data from either OR both tables?

Was it helpful?

Solution

You can try with:

SELECT MAX(location_a) AS location_a,
       MAX(refno_a) AS refno_a,
       MAX(location_b) AS location_b,
       MAX(refno_b) AS refno_b
FROM (
SELECT location AS location_a,
       refno AS refno_a,
       NULL AS location_b,
       NULL AS refno_b
FROM tableA
WHERE refno = '1234'
UNION ALL
SELECT NULL AS location_a,
       NULL AS refno_a,
       location AS location_b,
       location AS refno_b
FROM tableB
WHERE note = 'LN1234567') s

OTHER TIPS

Assuming you want matching locations on both side, you want a left join. Here is a simplified version:

SELECT a.location, b.location, a.refno, b.note
FROM tableA a LEFT JOIN
     tableB b
     on a.location = b.location
WHERE a.refno = '1234' and b.note = 'LN1234567';

If you actually want a cross join (different locations on the same row) and still want results, I think you need a union all:

SELECT a.location, b.location, a.refno, b.note
FROM tableA a CROSS JOIN
     tableB b
WHERE a.refno = '1234' and b.note = 'LN1234567'
UNION ALL
SELECT a.location, NULL, a.refno, NULL
FROM tableA
WHERE NOT EXISTS (SELECT 1 FROM tableB b WHERE b.note = 'LN1234567');
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top