如果最后一行的字段符合子句或子查询结果等于0,则插入

时间:2018-09-27 18:38:27

标签: mysql sql

我正在尝试使用以下内容

______________________________
| id | item (fk) | condition |
| 1  | 3         | NEW       |
| 2  | 3         | USED      |
| 3  | 2         | USED      |
______________________________

我要实现的目标如下:

例如,给定一个id为3的项目,如果满足以下两个条件之一,我想在该表中插入一个新行:

  1. 具有最大ID的行不是“ NEW”`
  2. 此项(id = 3)的条目countequal to 0

我到目前为止最接近的是:

INSERT INTO tableA (item, condition)
        SELECT (itemId, "NEW")  FROM ( 
                    SELECT condition, count(*) as rowCount
                    FROM tableA 
                    WHERE item = itemId 
                    ORDER BY id DESC LIMIT 1 ) a
            WHERE a.condition <> "NEW" OR a.rowCount = 0;

但是count(*)弄乱了顺序。有什么线索吗?

2 个答案:

答案 0 :(得分:2)

我将其视为没有GROUP BY的聚合子查询。这总是返回恰好一行,因此即使cnt0,您仍然会有一行:

INSERT INTO tableA (item, condition)
    SELECT a.itemId, a.condition
    FROM (SELECT @itemId as itemId, 'NEW' as condition,
                 COUNT(*) as cnt,
                 MAX(id) as max_id,
                 MAX(CASE WHEN condition = 'NEW' THEN id END) as max_new
          FROM tableA
          WHERE item = @itemId
         ) a
    WHERE cnt = 0 OR max_new is null or max_new < max_id;

答案 1 :(得分:1)

您需要一个子查询来获取该item的ID最大的行:

SELECT condition
FROM tableA
WHERE item = 3
ORDER BY id DESC
LIMIT 1

如果此item没有任何行,则此子查询将返回NULL。您可以使用null安全相等运算符来处理此问题。

INSERT INTO tableA (item, condition)
SELECT 3, "NEW"
FROM DUAL
WHERE NOT (
    SELECT condition
    FROM tableA
    WHERE item = 3
    ORDER BY id DESC
    LIMIT 1
) <=> "NEW"