SQL查询 - 使条件有条件?

时间:2015-11-03 16:02:43

标签: mysql insert insert-update

我有两个表(这些只是简化版):

`Locations`:
id  city  country  area
--  ----  -------  ----
71  C     X        E             
72  C     B        E             
73  C     F        G             
74  L     X        E
75  M     N        O
76  M     N        E          

`Findings`:
ID  city  country  area  resultVM
--  ----  -------  ----  --------
18                       empty
19  C                    lam  
20        X              lam8    
21                 E     pdg4   

现在,根据这两个数据,我想写一个填充第三个表的插入。它应该包含Location表中的所有id(Summed.locations_id显然是对Locations.id的引用),以及来自Findings表的匹配resultVM。结果应该是:

`Summed`:
locations_id   resultVM
------------   --------
71             lam        
72             lam        
73             lam        
74             lam8
75             empty
76             pdg4   

标准是:首先尝试匹配城市以在Findings表中找到resultVM,如果没有结果然后匹配国家,那么该区域,最后如果没有结果那么空行,其中没有城市/国家/地区已满。

目前我正在使用重复键上的4次插入/更新,但由于表非常大,需要花费大量时间。有谁知道这是否可以在单个更新/插入/任何内容(在MySQL中)完成? 谢谢!

2 个答案:

答案 0 :(得分:1)

尝试:

INSERT INTO `Summed`
SELECT
  `l`.`id`,
  COALESCE(
    `fcity`.`resultVM`,
    `fcountry`.`resultVM`,
    `farea`.`resultVM`,
    `fempty`.`resultVM`)
FROM
  `Locations` `l`
    LEFT JOIN `Findings` `fcity` ON `l`.`city` = `fcity`.`city`
    LEFT JOIN `Findings` `fcountry` ON `l`.`country` = `fcountry`.`country`
    LEFT JOIN `Findings` `farea` ON `l`.`area` = `farea`.`area`
    LEFT JOIN `Findings` `fempty` ON `fempty`.`city` = '' AND
                         `fempty`.`country` = '' AND
                         `fempty`.`area` = '';

SQL Fiddle demo

答案 1 :(得分:0)

您可以执行左连接。

 INSERT INTO Summed (locations_id,resultVM)
    SELECT Locations.`id` AS locations_id,(CASE WHEN Findings_city.`city` IS NOT NULL THEN Findings_city.`resultVM`
                           WHEN Findings_country.`country` IS NOT NULL THEN Findings_country.`resultVM`
                           WHEN Findings_area.`area` IS NOT NULL THEN Findings_area.`resultVM`
                            ELSE 'empty'END) AS resultVM
    FROM
    Locations 
    LEFT JOIN Findings Findings_city ON Locations.`city` = Findings_city.`city`
    LEFT JOIN Findings Findings_country ON Locations.`country` = Findings_country.`country`
    LEFT JOIN Findings Findings_area ON Locations.`area` = Findings_area.`area`
    GROUP BY Locations.`id`

这是SQL Fiddle Demo 希望这会有所帮助..