I suppose this is a very common question and possibly is duplicated, but I didn't know how to search it. This is my scenario: I have 3 tables: registers, foods and recipes. Tables structure simplified:
id | item_id | type (0 food|1 recipe)
(item_id can be whatever a food id or recipe id)
id | name | weight
id | name | num_ingredients
What I want is to query the registers table and return the food or recipe name (and some specific fields from each table, like weight in foods and num_ingredients in recipes) based on the type field being 0 or 1.
If the tables structure is not the best, I would thank to help me find the best solution. Thanks a lot in advance.
You can do this like so:
select r.id, r.type, f.name
from
Registers r
inner join Foods f on f.id = r.item_id and r.type = 0
union all
select r.id, r.type, c.name
from
Registers r
inner join Recipes c on c.id = r.item_id and r.type = 1
But your table structure isn't ideal. First of all, since r.item_id can contain an id from two tables, it is impossible to add a constraint that enforces referential integrity. You'll need a trigger to check it, which is more complex and slower.
Instead, I'd choose to make the relation the other way around:
Add a register_id to Foods and Recipes. Then, you can write your query like this:
select r.id, r.type, f.name
from
Registers r
inner join Foods f on f.register_id = r.id
union all
select r.id, r.type, c.name
from
Registers r
inner join Recipes c on c.register_id = r.id
That's almost the same, but you don't need the type and it allows you to make proper foreign key constraints.
You need to combine the two detail tables with a UNION
, and then JOIN
them with the Registers table using the ID
and type
fields.
SELECT item_id, name, data
FROM Registers r
JOIN (SELECT 0 type, id, name, weight as data
FROM Foods
UNION
SELECT 1 type, id, name, num_ingredients as data) x
ON r.item_id = x.id AND r.type = x.type
GolezTroi's answer where he does the UNION
after JOIN
is probably better, though, since it doesn't create a large temporary table before joining.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.