I have the following query
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));
Error:
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
I am not sure why is there any error. I am just inserting values fetched from other tables based on condition. I followed this answer which works for insert/select from a single table. But when I try to get value from other tables it doesn’t work.
What am I doing wrong?
2
Answers
You need parentheses around each subquery that’s being used to get a single value.
You also don’t need so much nesting.
Supposing that the
type
andvalue
columns uniquely identify the T2 rows, you could get the same output of your select query without using subqueries:Or:
You can use these queries in your insert query.
demo