【问题标题】:SQL Statement to auto-increment values in column if row exists without primary key如果行存在而没有主键,则 SQL 语句自动增加列中的值
【发布时间】:2014-11-11 17:37:00
【问题描述】:

我有一张包含这些数据的表格

mysql> SELECT * FROM prueba;
+----+------+------+------+
| id | U1   | U2   | cant |
+----+------+------+------+
|  2 | U123 | U124 |    2 |
+----+------+------+------+

每次执行该语句时,我都需要将 'cant' 增加 1。 但如果该行不存在,则必须创建它。 U1 和 U2 列是数据对,这意味着 U1,U2 对是唯一的,这就是搜索记录是否存在的条件。

这是我到目前为止所做的。

select U1,U2,cant,
    (
        case when exists (select U1,U2 from prueba where U1='U123'
        and U2='U124')
            then 1
            else 0
        end
    ) as tmp

    from prueba

【问题讨论】:

  • MAX(cant) + 1 这样的东西怎么样?

标签: mysql insert case increment


【解决方案1】:

insert-to-table-or-update-if-exists-mysql 中查看接受的答案。这个想法是使用 MySQL

INSERT INTO ... ON DUPLICATE KEY UPDATE ...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-10-17
    • 1970-01-01
    • 2014-12-07
    • 2018-06-05
    • 1970-01-01
    • 1970-01-01
    • 2012-06-20
    相关资源
    最近更新 更多