根据查询结果插入记录的最简单方法是什么?

时间:2017-02-15 14:46:57

标签: sql if-statement

我有一个带有几个外连接的查询,以获取每个用户的字段值。现在我需要为eula_date插入一个field_value行,如果stripe_id不为null但是eula_date为null。

这是我的疑问:

select u.id, v1.value as stripe_id, v2.value as eula_date
from hojeh_users as u
left outer join hojeh_community_fields_values as v1
    on v1.user_id = u.id and v1.field_id = 27
left outer join hojeh_community_fields_values as v2
    on v2.user_id = u.id and v2.field_id = 28

结果如下:

id  | stripe_id          | eula_date
----+--------------------+-------------------
943 | cus_8c44j6pZ8iN9eA | null 
----+--------------------+-------------------
944 | null               | null
----+--------------------+-------------------
949 | cus_8c2M4zm85BWKsN | 2017-02-01 2:03:57
----+--------------------+-------------------

我需要设置

如何实现这样的if语句:

if (v1.value not null && v2.value is null){
     INSERT INTO hojeh_community_fields_values 
     (column1, column2, column3,...columnN) 
     VALUES (value1, value2, value3,...valueN); 

我需要更新field_values表,以便我的结果显示:

id  | stripe_id          | eula_date
----+--------------------+-------------------
943 | cus_8c44j6pZ8iN9eA | 2017-01-01 0:0:0
----+--------------------+-------------------
944 | null               | null
----+--------------------+-------------------
949 | cus_8c2M4zm85BWKsN | 2017-02-01 2:03:57
----+--------------------+-------------------

1 个答案:

答案 0 :(得分:1)

INSERT INTO hojeh_community_fields_values 
     (user_id, field_id, value) 
select 
     id, 28, '2017-01-01 0:0:0'
from hojeh_users as u
left outer join hojeh_community_fields_values as v1
    on v1.user_id = u.id and v1.field_id = 27
left outer join hojeh_community_fields_values as v2
    on v2.user_id = u.id and v2.field_id = 28
where v1.value is not null and v2.value is null