UPDATE不会影响某些行

时间:2014-09-24 14:28:13

标签: mysql sql

我的问题是使用其他表中的数据更新一个表中的数据。我的SELECT查询获取所有需要的行,但UPDATE查询不会产生任何影响。怎么了? 这是SELECT查询:

SELECT 
t1.id,
COUNT(*) 
FROM table_1 as t1 
LEFT JOIN table_2 as t2 
    ON t1.system_id =  t2.system_id 
    AND t1.tenant_id = t2.tenant_id 
    AND name LIKE '%<ohne>' 
    AND t2.created_by_id = '1'  
    WHERE t1.system_project_id IS NULL     

这是UDATE查询

UPDATE table_1 as t1  
LEFT JOIN table_2 as t2 
ON t1.system_id =  t2.system_id 
   AND t1.tenant_id = t2.tenant_id 
   AND name LIKE '%<ohne>' 
   AND t2.created_by_id = '1' 
   SET t1.system_project_id = t2.id 
   WHERE t1.system_project_id IS NULL

表结构:

CREATE TABLE table_1 (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `tenant_id` int(11) DEFAULT NULL,
  `system_id` int(11) NOT NULL,      
  `system_project_id` int(11) DEFAULT NULL,
)

CREATE TABLE `table_2` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `created_by_id` int(11) NOT NULL,
  `system_id` int(11) NOT NULL,
  `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
  `tenant_id` int(11) DEFAULT NULL,
)

示例数据:

table_1: 
 id: 1
 tenant_id:1
 system_id:1
 system_project_id:NULL

table2:
 id:1
 tenant_id:1
 system_id:1
 name:blabla<ohne>
 created_by_id:1

UPDATE后的预期数据:

 table_1: 
  id: 1
  tenant_id:1
  system_id:1
  system_project_id:1

我稍微更新了我的查询,现在看起来如何:

IF EXISTS (
SELECT t2.id FROM table_1 as t1
LEFT JOIN table_2 as t2 ON t1.system_id =  t2.system_id 
AND t1.tenant_id = t2.tenant_id AND name LIKE '%<ohne>' AND syp.created_by_id = '1' 
WHERE t1.system_project_id IS NULL 
) 
THEN 
    UPDATE table_1 as t1_1
    SET t1.system_project_id =  t2.id 
    FROM table_2 as syp WHERE t1_1.system_id =  t2.system_id 
    AND t1_1.tenant_id = t2.tenant_id AND name LIKE '%<ohne>' AND t2.created_by_id = '1' 
    AND t1_1.system_project_id IS NULL;
ELSE
    INSERT INTO table_2 (created_by_id, updated_by_id, system_id, created_at, updated_at,             name, tenant_id)
    SELECT 1,1, t1_1.system_id, NOW(), NOW(), CONCAT(t3.name,'<ohne>'), t1_1.tenant_id
    FROM table_1 as t1_1
    LEFT JOIN table_3 as t3 ON rem.system_id = t3.id
    WHERE t1_1.system_project_id IS NULL;
END IF; 

但是它仍然不起作用。 table_3只是获取'name'的连接表。

1 个答案:

答案 0 :(得分:1)

尝试此选择语句。

SELECT t2.id, t1.id, t1.system_project_id FROM table2 AS t2, table_1 AS t1
LEFT JOIN table_2 as t2 ON   t2.id = t1.system_project_id
WHERE t1.tenant_id = t2.tenant_id 
AND t1.system_id =  t2.system_id
AND name LIKE '%<ohne>' AND t2.created_by_id = '1' 
AND t1.system_project_id IS NULL`enter code here`

table_2上的左连接可以在结果表中创建t1.id null。这些是table_2中的行,其中缺少相应的table_1行。

你不应该使用&#34;并且命名为LIKE&#39;%&#39; &#34;作为ON条款。

其中t1.id IS NOT NULL,更新 其中t1.id IS为NULL,插入