Q: Do I need a IF or IF Exists clause?
A: No.
What you need to recognize is that your query is returning a semi-Cartesian product.
The syntax you have is equivalent to:
SELECT m.*
, d.*
FROM moms m
CROSS
JOIN dads d
WHERE m.Color = 'Red'
OR d.ColorName = 'Red'
Basically, every row from moms
is being matched to every row from dads
. (Run the query without a WHERE clause, if you have 10 rows in moms
and 10 rows in dads
, you'll get back a total of 100 rows.
The WHERE
clause is just filtering out the rows that don't meet the specified criteria.
Usually, when we use a SQL join operation, we include some predicates that specify which rows from one table are to match which rows from another table. (Typically, a foreign key matches a primary key.)
(I recommend you ditch the old-school comma syntax for the JOIN operation, and use the newer JOIN
keyword instead.)
Firstly, what result set do you expect to be returned?
If you want rows from moms
, you could get those with this query:
SELECT m.*
FROM moms m
WHERE m.Color = 'Red'
If you want rows from dads
, then this:
SELECT d.*
FROM dads d
WHERE d.ColorName = 'Red'
If the columns in the moms
and dads
tables "line up", in terms of the number of columns, the order of the columns and the datatypes of the columns, you could use a UNION ALL set operator to combine the results from the two queries, although we would typically also include a discriminator column, to tell which query each row was returned from:
SELECT 'moms' AS `source`
, m.id AS `id`
, m.Name AS `name`
, m.Number AS `number`
, m.Color AS `color`
FROM moms m
WHERE m.Color = 'Red'
UNION ALL
SELECT 'dads' AS `source`
, d.id AS `id`
, d.FullName AS `name`
, d.Phone AS `number`
, d.ColorName AS `color`
FROM dads d
WHERE d.ColorName = 'Red'
Beyond those suggestions, it's hard to provide any more help, absent a clearer definition of the actual resultset you are attempting to return.