如果选择输出<>则插入MySQL值

时间:2014-07-25 12:26:59

标签: mysql sql

我正在为跟踪各种对象的数量和类型的项目编写记录系统。 我需要编写一个Insert Query,只有在上次自上次更改Quantity(qty)时才会导入。

这是获取最后插入数量的查询:

SELECT qty FROM `qty` WHERE object='object_name' AND type='type' ORDER BY UNIX_TIMESTAMP(timestamp) DESC LIMIT 1

但是我现在怎么说:只有当Programm给出的数量不是上面查询给出的数量时才导入

编辑: 这是Normal插入:

INSERT INTO `qty` (qty, object, type) VALUES ("quantity", "object_name", "type")

编辑: 我现在就开始工作了! 谢谢大家的回复!你们真棒!)

INSERT INTO qty (qty, object, type)
SELECT * FROM (SELECT 'qty-value', 'object-value', 'type-value') AS tmp
WHERE NOT EXISTS (
 SELECT * FROM (SELECT qty FROM `qty` WHERE object = 'object-value' AND type = 'type-value' ORDER BY UNIX_TIMESTAMP( timestamp ) DESC LIMIT 1) as lastQTY WHERE qty = "qty-value"
) LIMIT 1;

2 个答案:

答案 0 :(得分:0)

如果您想要insert个新值,请尝试将新值与旧值匹配。如果匹配,则过滤掉行。我认为关键是使用insert . . . select而不是insert . . . values

以下提出了这个想法:

INSERT INTO qty(qty, object, type) 
    select @quantity, @object_name", @type
    from (select @quantity as quantity, @object_name as object_name, @type as type
         ) as newrow left outer join
         (SELECT qty.*
          FROM qty
          WHERE object = @object_name AND type = @type
          ORDER BY UNIX_TIMESTAMP(timestamp) DESC
          LIMIT 1
         ) oldrow
         on newrow.quantity = oldrow.quantity and
            newrow.object_name = oldrow.object_name and
            newrow.type = oldrow.type
    where oldrow is null;

答案 1 :(得分:0)

认为这样做会。

这将获取您的输入值,将其与子查询连接以获取对象和类型的最新时间戳,然后将其与qty表连接以获取最新时间戳的列数量值和数量与新数量相同。

WHERE子句然后检查最新的qty的值是否为NULL(即,假设qty不能合法地为NULL,则没有找到记录)

INSERT INTO `qty_test` (qty, object, type) 
SELECT a.qty, a.object, a.type
FROM 
(
    SELECT 1 AS qty, 1 AS object, 1 AS type
) a
LEFT OUTER JOIN 
(
    SELECT object, type, MAX(timestamp) AS max_timestamp
    FROM qty_test
    GROUP BY object, type
) b
ON a.object = b.object
AND a.type = b.type
LEFT OUTER JOIN qty_test c
ON a.object = c.object
AND a.type = c.type
AND a.qty = c.qty
AND b.max_timestamp = c.timestamp 
WHERE c.qty IS NULL