I've a table t1. And I want to insert data into this table based on query result of another tables t2, t3 etc.
I'm doing it like this-
Insert into table_t1 (column1,column2,column3,column4)
Select col1, col2, Have_to_check_condition_here_and_then_insert_value, Have_to_check_condition_here_and_then_insert_value from table_t2
where condition;
The problem I'm facing is how to put values inside column3 and column4 which comes from table_t3 and table_t4 and that too conditionally, it means if something is true then I'll put value_something otherwise value_another_thing. Table 3rd and 4th are connected with 2nd table on a particular column.
CodePudding user response:
With as much info as you posted, that would be something like this:
INSERT INTO table_t1 (col1,
col2,
col3,
col4)
SELECT b.col1,
c.col2,
CASE
WHEN b.amount > 1000 THEN c.one_value
ELSE c.some_other_value
END AS col3,
--
CASE
WHEN c.TYPE = 'A' THEN b.some_column
WHEN c.TYPE IN ('B', 'C') THEN c.another_column
ELSE NULL
END AS col4
FROM table_t3 b JOIN table_t4 c ON b.id = c.id