简体   繁体   English

MySQL:根据字段为0或1从2个不同的表中获取信息的特定查询

[英]MySQL: Specific query to obtain info from 2 different tables based of a field being 0 or 1

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. 这是我的情景:我有3个表:寄存器,食物和食谱。 Tables structure simplified: 表格结构简化:

Registers 寄存器

id | id | item_id | item_id | type (0 food|1 recipe) 类型(0食品| 1食谱)

(item_id can be whatever a food id or recipe id) (item_id可以是食物ID或食谱ID)

Foods 食品

id | id | name | 名字| weight 重量

Recipes 食谱

id | id | name | 名字| num_ingredients 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. 我想要的是查询寄存器表并根据类型字段为0或1返回食物或食谱名称(以及每个表中的一些特定字段,如食物中的重量和食谱中的num_ingredients)。

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. 首先,由于r.item_id可以包含来自两个表的id,因此无法添加强制引用完整性的约束。 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. 将register_id添加到食物和食谱中。 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. 您需要将两个细节表,并结合UNION ,然后JOIN与使用的寄存器表他们IDtype的字段。

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. GolezTroi的回答是他在JOIN之后进行UNION可能会更好,因为它在加入之前不会创建一个大的临时表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM