[英]Insert into a table while selecting from two tables have no relation with each other
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|
+-----------------------------------------------+
我可以通过执行多个查询和选择来完成此操作,但我想知道是否有一个查询可以执行此操作? 没有联接(当行中有很多记录时,联接很健壮,-我想??-)
另外,您可能已经注意到,如果没有匹配项,我希望该proc使用ID默认为0,我想我可以通过使用COALESCE来实现
编辑:假设someField是AUTO INCREMENTING
这有点棘手,因为您不允许比赛。 在其他数据库中,您将使用full outer join
。 在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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.