-1

I would like to get the resulting row if the foreign id present in Table A or in Table B.

I have 3 tables: events, pdf_results and live_Results. I would like to select all events with pdf_results OR live_Results.

I have tried following query but it's not working when results are available in both tables.

SELECT
  events.*,
  live_results.id,
  pdf_results.id
FROM events
LEFT JOIN pdf_results
  ON pdf_results.eventId = events.id
LEFT JOIN live_Results
  ON live_Results.eventId = events.id;

Here is SQL Fiddle Demo

Laxmi
  • 3,830
  • 26
  • 30
Mike Ross
  • 2,942
  • 5
  • 49
  • 101
  • 1
    Can we get a sample of your database structure + content ? – giolliano sulit Nov 02 '17 at 00:59
  • 1
    @giollianosulit I have added demo fiddle in the question. – Mike Ross Nov 02 '17 at 01:17
  • Hi. "get the resulting row if the foreign id present in Table A or in Table B" is not clear. "select all events with pdf_results OR live_Results" is also not clear, but is maybe closer to making sense. Also "it's not working" and "when results are available in both tables" are not clear. Please use enough words & phrases & sentences to say what you mean. Also please read & act on [mcve]. That includes DDL, DML, input, output & desired output. (And when you have an sqlfiddle link please also have relevant code in your question.) – philipxy Nov 02 '17 at 02:15
  • `union` returns rows that are in a left table *or* are in a right table. `join` returns rows whose subrows are in a left table *and* in a left table. So a (`join` with) `on` or `where` can only return rows with this `or` that *and* the appropriate subrows are in each table. `left join` returns rows returns rows that are in an `inner join` *or* that don't and have a subrow in a left table and have `null` for each column of a right table. So again some queries of a special form with "or" and/or "and" can be phrased with it. https://stackoverflow.com/a/33952141/3404097 – philipxy Nov 02 '17 at 02:19

2 Answers2

0

How about just using exists?

SELECT e.* 
FROM events e
WHERE EXISTS (SELECT 1 FROM pdf_results pr WHERE pr.eventId = e.id) OR
      EXISTS (SELECT 1 FROM live_Results lr WHERE lr.eventId = e.id);
Gordon Linoff
  • 1,242,037
  • 58
  • 646
  • 786
0

You can join with a UNION query:

SELECT e.*, r.result_type
FROM events AS e
JOIN (SELECT eventId, 'pdf' AS result_type FROM pdf_results
      UNION ALL
      SELECT eventId, 'live' AS result_type FROM live_results) AS r
ON e.id = r.eventId

Adding the result_type column allows us to know which results table it matched, and we'll get two rows if it matches both.

You could also use your original query, and add:

WHERE pdf_results.eventId IS NOT NULL OR live_results.eventId IS NOT NULL

You won't get two rows when it matches twice, but you'll be able to tell from the two eventId columns which results table it was found in.

Barmar
  • 741,623
  • 53
  • 500
  • 612