我有以下疑问

insert into T1 (code, code2, type, is_default, m_order, m_type, title, created_by)
select t.*
from    (select a.code from (select code from T2 where type = 171 and value = 'ABC') a,
         select b.code from (select code from T2 where type = 170 and value  = 'D') b,
         'Value', 1, 1, 1, 'Type', 'System'
        UNION ALL
        select c.code from (select code from T2 where type = 171 and value = 'DEF') c,
        select d.code from (select code from T2 where type = 170 and value = 'D') d,
       'Value', 1, 2, 2, 'Loc', 'System'
        ) t
where not exists (select ... (with joins));

错误:

SQL Error [1064] [42000]: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'select b.code from (select code from T2 where type = 170 an' at line 4

我不确定为什么会有任何错误.我只是根据条件插入从其他表获取的值.我遵循了this answer,它适用于从单个表进行插入/ Select .但当我试图从其他表中获取价值时,它不起作用.

我做错了什么?

推荐答案

用来获取单个值的每个子查询都需要用括号括起来.

你也不需要这么多的嵌套.

INSERT INTO T1 (code, code2, type, is_default, m_order, m_type, title, created_by)
SELECT * FROM (
    SELECT (select code from T2 where type = 171 and value = 'ABC'),
           (select code from T2 where type = 170 and value  = 'D'),
           'Value', 1, 1, 1, 'Type', 'System'
    UNION ALL
    SELECT (select code from T2 where type = 171 and value = 'DEF'),
           (select code from T2 where type = 170 and value = 'D'),
           'Value', 1, 2, 2, 'Loc', 'System'
) AS x
WHERE NOT EXISTS (SELECT ...)

Mysql相关问答推荐

MySQL 8.0.34-从后端系统管理AWS RDS上的持久连接内存使用

如何使用GROUP BY调优简单SQL查询

如何将左联接的小计/总计行中的所有列作废

版本升级到5.0.0后在QueryDSL中使用Enum时出错

SQL Select 最大值和平均值

将 JSON 类型的列与特定字符串值进行比较

如何找到每个user_id每个产品的买家类型数量?

如何解码存储在带有type*:前缀的base64中的数据?

MySQL CHECK 约束以确保记录不使用自动增量 ID 引用自身?

MySQL:根据条件查找某些用户的行位置

使用来自另一个表 mysql 的值将新行插入到表中

SQL / MySQL:如何在WHERE IN中判断类似于OR的AND逻辑

如何在每个国家/地区查询 GHTorrent(类 SQL 语言)的最常用语言

查找同时玩过这两种游戏的玩家

了解 SQL 中的元组语法

Select 在同一天售出不同活动门票的收银员

如何使主键从 1000 开始?

MySQL 中的 VARCHAR(255) 和 TINYTEXT 字符串类型有什么区别?

电话号码和地址的mysql数据类型

'LIKE ('%this%' OR '%that%') and something=else' 不起作用