如果条目不存在,则插入 table 列

Insert into table column if entry does not exist

在 Liquibase 中,如果尚未设置值,我想插入值。对于正常的插入,我怀疑如果值已经存在,插入的值将覆盖先前的值。如果它不存在,我希望它只插入。这能做到吗?

现在我正在使用如下所示的插件:

<insert tableName="state">
  <column name="name" value="fooFoo"/>
  <column name="enabled" valueBoolean="true"/>
</insert>

你可以参考下面的问题:

MySQL: Insert record if not exists in table

只需在 Liquibase 中使用 < sql > 标签即可。

希望对您有所帮助。

编辑:

INSERT INTO 状态(名称,已启用) SELECT * FROM (SELECT 'fooFoo', 'true') AS tmp 哪里不存在( SELECT 名称来自状态名称 = 'fooFoo' ) 限制 1

< /sql >

正确的方法是使用 preConditions.

有一个 <sqlCheck> preCondition

sqlCheck

Executes an SQL string and checks the returned value. The SQL must return a single row with a single value. To check numbers of rows, use the “count” SQL function. To check for ranges of values, perform the check in the SQL and return a value that can be easily compared against.

<sqlCheck expectedResult="1">SELECT COUNT(1) FROM pg_tables WHERE TABLENAME = 'myRequiredTable'</sqlCheck>

有了它,您的 changeSet 将如下所示:

<changeSet id="foo" author="bar">
    <preConditions onFail="MARK_RAN">
        <sqlCheck expectedResult="0">
            SELECT COUNT(*) FROM state WHERE name='fooFoo' AND enabled=true;
        </sqlCheck>
    </preConditions>
    <insert tableName="state">
      <column name="name" value="fooFoo"/>
      <column name="enabled" valueBoolean="true"/>
    </insert>
</changeSet>