在添加新资产之前使用SQL检查重复

时间:2016-09-01 04:11:10

标签: sql postgresql

我有这样的表资产:

id  status  revision  EAN
-------------------------
1   Published    0     1
1   Published    1     2
1   Deleted      2     3
2   Published    0     4
2   Draft        1     5

在添加新资产之前,我想检查表中的EAN,如果资产的状态已删除,则可以重复使用此资产的EAN(这意味着1,2,3可以用于新资产),否则,我不能在表中使用ean(不能使用4,5)。

我在SQL中使用count来检查> 0 - >重复:

select count(*) 
from Asset a 
where a.ean = '1' 
  and a.id <> 0 
  and a.status != 'Deleted'
  and a.revision = (select max(a1.revision) 
                    from Asset a1 
                    where a1.id = a.id)

但是对于哪个资产没有状态已删除的情况不适合。

有人能给我一些反馈吗?

请帮帮我。 感谢

2 个答案:

答案 0 :(得分:0)

我认为,你的查询混淆了一些东西。你只计算你正在搜索的EAN的确切线。您可以使用您的EAN中的匹配ID计算所有行,如下所示:

<fieldset>
  <legend>Välj färgmarkering</legend>
  <form action="../action/return.html" method="get">

    <span class="box blue">
        <input id="button1" accesskey="1" type="radio" value="1" name="radio-input" title="Alt+1">
        <label for="button1">Blue</label>
    </span>

    <span class="box green">
        <input id="button2" accesskey="2" type="radio" value="2" name="radio-input" title="Alt+2">
        <label for="button2">Green</label>
    </span>

    <span class="box orange">
        <input id="button2" accesskey="2" type="radio" value="2" name="radio-input" title="Alt+2">
        <label for="button2">Orange</label>
    </span>

    <span class="box yellow">
        <input id="button2" accesskey="2" type="radio" value="2" name="radio-input" title="Alt+2">
        <label for="button2">Yellow</label>
    </span>

    </form>
</fieldset>

您甚至可以添加上次修订的支票,如下所示:

select count(*) from Asset
where id = (
select id 
from Asset a 
where a.EAN = 1)
and status='Deleted'

答案 1 :(得分:0)

我已经完成了sql: select count(*) from Asset a where a.ean=? and a!=? and not exist(select * from Asset a1 where a1.id = a.id and a.status ='Deleted'). 谢谢大家。