Ted
Ted

Reputation: 3875

PHP MYSQL SELECT even if some are empty

I am not too familiar with SQL, but I need to select from 3 tables.

I can go:

SELECT * FROM tbl1, tbl2, tbl3 WHERE ID=3

but there is a chance that tbl3 is does not have any rows with ID 3, and chances are that tbl1 has a few.

tbl2 should have only one row.

I would still like to get the rows in the other tables.

How can I accomplish this ?

Thanks up ahead!

Upvotes: 1

Views: 372

Answers (2)

Doug Kress
Doug Kress

Reputation: 3537

How do the three tables relate? The condition 'WHERE ID=3' is a little ambiguous - does ID exist in all three tables, and you want all records from each table where ID = 3?

The bottom line is you need to use a LEFT JOIN to join the tables together, but it's hard to give an example without knowing how the tables relate.

Making some assumptions:

SELECT *
FROM tbl1
LEFT JOIN tbl2 ON tbl2.tbl1_id = tbl1.id
LEFT JOIN tbl3 ON tbl3.tbl1_id = tbl1.id
WHERE tbl1.id = 3;

Upvotes: 1

carlgcode
carlgcode

Reputation: 255

Do seperate queries of each table, then do a row count of those queries, then with the results
you can do if elseif else statements to do wat you want to do.

Upvotes: 0

Related Questions