Forum Moderators: open

Message Too Old, No Replies

Selecting from multiple tables

         

Medianeer

1:00 pm on Sep 28, 2009 (gmt 0)

10+ Year Member



I'm trying to select information from several tables. The number of records on the 2nd table don't match the number of records of the 1st table. I want to get all records regardless of whether there's a record on the 2nd table or not. For example:

Table "animal"
+----+------+
¦ id ¦ name ¦
+----+------+
¦ a1 ¦ dog ¦
¦ a2 ¦ fish ¦
¦ a3 ¦ cat ¦
¦ a4 ¦ bird ¦
+----+------+

Table "pets"
+----+-----+
¦ id ¦ own ¦
+----+-----+
¦ a1 ¦ yes ¦
¦ a3 ¦ yes ¦
+----+-----+

Basically, "pets" table doesn't have a record for all "animal" ids. When selecting records using this:

SELECT
animal.id, animal.name, pets.own
FROM
animal, pets
WHERE
animal.id = pets.id

Returns this:

+----+------+-----+
¦ id ¦ name ¦ own ¦
+----+------+-----+
¦ a1 ¦ dog ¦ yes ¦
¦ a3 ¦ cat ¦ yes ¦
+----+------+-----+

My question is how do I make the query return this:

+----+------+-----+
¦ id ¦ name ¦ own ¦
+----+------+-----+
¦ a1 ¦ dog ¦ yes ¦
¦ a2 ¦ fish ¦ ¦
¦ a3 ¦ cat ¦ yes ¦
¦ a4 ¦ bird ¦ ¦
+----+------+-----+

I want the query to return all records regardless of whether table pets has an entry for it or not.

Anybody? ;-)

Medianeer

2:02 pm on Sep 28, 2009 (gmt 0)

10+ Year Member



Got it!

SELECT animal.id, animal.name, pets.own
FROM animal LEFT JOIN pets ON animal.id = pets.id