MySQL INSERT 条件数据 : Check if a value exists in another table in order to insert values into a third table

标签 mysql sql

我有4张 table

1/列表文章

enter image description here

2/cmd-moy-j

enter image description here

3/cmd-药物

enter image description here

4/cmd-营养

enter image description here

首先我需要检查“cmd-moy-j”.“Famille”是否为空。如果是这样,我需要检查“cmd-moy-j”。“代码文章”是否存在于“cmd-medicaments”或“cmd-alimentation”或“cmd-consommables”表中,以便添加此“代码文章”到一个名为“liste-articles”的表。您可以在以下算法中查看详细信息

我想这样做:(只有一个 MySQL 请求)

If 'cmd-moy-j.Famille' = "" (is empty)

then{

if ('cmd-moy-j.Code Article' Exists in 'cmd-medicaments')

 then 
 INSERT a new row to 'liste-articles' table with:
 liste-articles.Famille = "MEDICAMENT"
 liste-articles.Code Article = cmd-moy-j.Code Article

else if ('cmd-moy-j.Code Article' Exists in 'cmd-alimentation')

 then
 INSERT a new row to 'liste-articles' table with:
 liste-articles.Famille = "ALIMENTATION"
 liste-articles.Code Article = cmd-moy-j.Code Article

else INSERT a new row to 'liste-articles' table with: liste-articles.Famille = "NULLL" liste-articles.Code Article = cmd-moy-j.Code Article }

感谢您的帮助。 问候。

最佳答案

因此,您正在尝试根据存储文章的表更新所有文章列表系列。尝试这个查询:

UPDATE list-articles A
INNER JOIN cmd-moy-j B ON A.`Code Article`=B.`Code Article`
SET A.Famille=(
  CASE WHEN EXISTS (SELECT 1 FROM cmd-medicaments C 
                    WHERE B.`Code Article`=C.`Code Article` LIMIT 1)
       THEN 'MEDICAMENT'
       WHEN EXISTS (SELECT 1 FROM cmd-alimentation D 
                    WHERE B.`Code Article`=D.`Code Article` LIMIT 1)
       THEN 'ALIMENTATION'
       ELSE 'NULLL'
  END
)
WHERE A.Famille IS NULL OR A.Famille='NULLL' OR A.Famille='';

请参阅以下链接以获取见解:

MySQL CASE Expression
MySQL Join Made Easy
MySQL UPDATE JOIN

关于MySQL INSERT 条件数据 : Check if a value exists in another table in order to insert values into a third table,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49232742/

相关文章:

html - 如何使用 Perl 编码和解码 "Acute accented characters"

php - Laravel Eloquent ORM 查询关系内的关系

MySQL 触发器 UPDATE 未触发

sql - 选择独特的列组合

mysql - 按升序排列 MySQL 表(数字)

mysql - Mysql中使用HEX()转换字符编码

mysql - 使用子字符串后mysql查询中出现多个警告

python - 使用Python和SQLite创建表,没有这样的表

sql anywhere 5.5 数据库连接到 sql anywhere 12

MySQL根据两个表选择行