【发布时间】:2022-12-07 13:35:45
【问题描述】:
我想使用同一字段中另一条记录的数据插入一条新记录。在这种情况下,新租户需要使用与其父“0904ba44-9d41-418a-bbd8-2c70506c3432”相同的域名。
我的直觉告诉我带有 JOIN 的那个更好。有更多智慧的人可以解释为什么我的直觉是对还是错。想发展更好的优化技能。
我有两个 INSERTs 可以工作。
这个带有子查询,行之有效。
INSERT INTO tenant (tenant_uuid, secondary_domain)
VALUES (
UUID_TO_BIN(UUID()),
(SELECT secondary_domain FROM (SELECT top_level_domain FROM tenant WHERE tenant_uuid = UUID_to_bin('0904ba44-9d41-418a-bbd8-2c70506c3432')) as b ));
有了这个解释。
+-----+--------------+---------------+-------------+-----------+------------------------+------------+----------+----------+-------+-----------+--------+
| id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+-----+--------------+---------------+-------------+-----------+------------------------+------------+----------+----------+-------+-----------+--------+
| '1' | 'INSERT' | 'tenant' | NULL | 'ALL' | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| '2' | 'SUBQUERY' | '<derived3>' | NULL | 'system' | NULL | NULL | NULL | NULL | '1' | '100.00' | NULL |
| '3' | 'DERIVED' | 'tenant' | NULL | 'const' | 'PRIMARY tenant_uuid' | 'PRIMARY' | '16' | 'const' | '1' | '100.00' | NULL |
+-----+--------------+---------------+-------------+-----------+------------------------+------------+----------+----------+-------+-----------+--------+
这个使用连接,有效
INSERT INTO tenant (tenant_uuid, secondary_domain)
VALUES (
UUID_TO_BIN(UUID()),
(SELECT b.secondary_domain FROM tenant a INNER JOIN tenant b on a.tenant_uuid = b.tenant_uuid WHERE b.tenant_uuid = UUID_to_bin('0904ba44-9d41-418a-bbd8-2c70506c3432'));
用这个解释
+------+--------------+-----------+-------------+----------+------------------------+------------+----------+----------+-------+-----------+----------------+
| # id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra |
+------+--------------+-----------+-------------+----------+------------------------+------------+----------+----------+-------+-----------+----------------+
| '1' | 'INSERT' | 'tenant' | NULL | 'ALL' | NULL | NULL | NULL | NULL | NULL | NULL | NULL |
| '2' | 'SUBQUERY' | 'a' | NULL | 'const' | 'PRIMARY tenant_uuid' | 'PRIMARY' | '16' | 'const' | '1' | '100.00' | 'Using index' |
| '2' | 'SUBQUERY' | 'b' | NULL | 'const' | 'PRIMARY tenant_uuid' | 'PRIMARY' | '16' | 'const' | '1' | '100.00' | NULL |
+------+--------------+-----------+-------------+----------+------------------------+------------+----------+----------+-------+-----------+----------------+
【问题讨论】:
-
INSERT .. VALUES用法明显错误。使用INSERT .. SELECT。
标签: mysql sql-insert