Fruits Animals
+------------------+------------------------+
| fruID fruDesc | animalID animalDesc |
| | |
| 0 Unknown | 0 Unknown |
| 1 Apple | 1 Bird |
| 2 Banana | 2 Tiger |
| 3 Microsoft | 3 Etc |
+------------------+------------------------+
NoBrain
+-------------------------------------------+
| someField fruID animalID dateRecorded |
| |
| 0 3 2 now |
+-------------------------------------------+
我正在使用 MySQL 并尝试编写一个过程,该过程接受两个文本字段(预计为 fruDesc 和animalDesc),找到它们的相关 ID 并将这些列插入表中。
在上面的场景中,我应该能够调用 Cool_proc('Banana', 'Tiger', 'reallydoesntmatter') 并且应该插入 NoBrain TBL 相应的行:
NoBrain
+-----------------------------------------------+
| someField fruID animalID dateRecorded |
| |
| 2 2 2 reallydoesntmatter|
+-----------------------------------------------+
我可以通过执行多个查询和选择来完成此操作,但我想知道是否可以通过单个查询来完成此操作?不加入(当行中有很多记录时,加入很强大,-我想??-)
此外,您可能已经注意到,如果没有匹配项,我希望该过程使用 ID 默认值 0,我想我可以通过使用 COALESCE 来实现此目的
编辑:假设 someField 是自动增量
最佳答案
这有点棘手,因为不允许匹配。在其他数据库中,您将使用完全外部联接
。在 MySQL 中,您将使用 union all
和聚合:
insert into nobrain(fruid, aniamlid, daterecorded)
select max(f.fruid), max(animalid), now()
from ((select f.fruid, NULL as animalid, NULL as animalDesc
fruits f
where f.frudesc = 'Banana'
) union all
(select a.animalid, NULL, animalDesc
from animals a
where a.animalDesc = 'Tiger'
)
) af;
关于mysql - 插入一个表,同时从两个表中选择,彼此没有关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803976/