Tables cats
and dogs
are made up of different attributes. I want to keep track of feeding (say animal_fed
, food_type
, food_quantity
, date
, ...).
Table feeds
has animal_id INTEGER
, table_name VARCHAR(50)
(could be cats
or dogs
, but there will be more species) and other fields.
It is a pain (if even possible) to select from feeds
retrieving also informaiton on the animal been fed (similarly with join
).
How can I better approach this?
Is using a parent table good?
Or if my approach is good how can I join to get, say, all the feeds
information plus the animal name
?
There are several ways to improve it, but your solution is nearly good:
animals
table will have all columns from both table. And you will have column animal_type
which will be either dog or cat.FROM animals WHERE id IN ( ANIMAL_ID_FROM_PREVIOUS_RESULT )
. Then you have to merge these in your application.dogs
table, the cats
table and the feeds
table and you create r_dog_feed
and r_cat_feed
tables. They will have feed_id
which will refer to feeds
table and then either dog_id
or cat_id
. Then you can write SQL using UNION:SELECT dogs.name as name, feeds.* FROM r_dog_feed
JOIN dogs ON dogs.id = r_dog_feed.dog_id
JOIN feeds ON feeds.id = r_dog_feed.feed_id
UNION
SELECT cats.name as name, feeds.* FROM r_cat_feed
JOIN cats ON cats.id = r_cat_feed.cat_id
JOIN feeds ON feeds.id = r_cat_feed.feed_id