将sql中的两个值相互比较

时间:2014-08-29 09:59:38

标签: mysql sql tsql magento compare

我有一个双重图像的magento数据库,我想删除它们,但首先我要用sql查询检测它们。

我试过这段代码

select t1.VALUE from catalog_product_entity_media_gallery t1 
join catalog_product_entity_media_gallery t2 on (t1.value = t2.value)

这一个:

  select * from catalog_product_entity_media_gallery where value=value 

和这一个:

select
*
from
(
    select
        value
    from
        catalog_product_entity_media_gallery
    group by
        value
    having count(*) > 1
) as t
inner join catalog_product_entity_media_gallery on (
    catalog_product_entity_media_gallery.value = t.value
)

第一个给出错误,第二个和第三个给出每个产品。

this is my small test database

2 个答案:

答案 0 :(得分:0)

试试这个:

select
*
from (
    select 
        entity_id,attribute_id,value,
        MIN(value_id) value_id
    from catalog_product_entity_media_gallery
    group by
        entity_id,attribute_id,value
    having COUNT(*) > 1
) A1
inner join catalog_product_entity_media_gallery A2 on
    A1.entity_id = A2.entity_id and
    A1.attribute_id = A2.attribute_id and
    A1.value = A2.value and
    A1.value_id = A2.value_id

答案 1 :(得分:0)

您可以按值获取最小ID,然后除了其他记录:

select
*
from catalog_product_entity_media_gallery t1
where exists
( select * from 
  (select  value, min(value_id) as min_value_id
    from   catalog_product_entity_media_gallery
    group by  value
  ) as t2
  where t1.value=t2.value and t1.value_id=t2.min_value_id
)

如果要删除重复的行,则更改存在为不存在。

delete
from catalog_product_entity_media_gallery t1
where not exists
( select * from 
  (select  value, min(value_id) as min_value_id
    from   catalog_product_entity_media_gallery
    group by  value
  ) as t2
  where t1.value=t2.value and t1.value_id=t2.min_value_id
)