如何选择重复以获得正确的结果?

时间:2013-09-19 00:45:59

标签: mysql sql prestashop

你能帮我写一下有效的SQL查询吗?

我需要选择所有重复的link_rewrite。 仅当id_shop,id_lang相同时才重复。

查看完整代码:https://github.com/Ha99y/prestashopCleanURLs/blob/master/PS15/cleanurls.php#L49

-------------------------------------------------------
| id_product  |  id_shop  |  id_lang  |  link_rewrite |
-------------------------------------------------------
|     1       |    1      |     1     |   ipod-nano   |
|     1       |    1      |     2     |   ipod-nano   |
|     2       |    1      |     1     |   ipod-nano   |
|     2       |    1      |     2     |   ipod-nano   |
|     8       |    2      |     1     |   ipod-nano   |
|     8       |    2      |     2     |   ipod-nano   |
-------------------------------------------------------

SQL:

SELECT * FROM `ps_product_lang`
WHERE `link_rewrite`
IN (SELECT `link_rewrite` FROM `ps_product_lang`
GROUP BY `link_rewrite`, `id_lang`
HAVING count(`link_rewrite`) > 1)

任何帮助表示赞赏

3 个答案:

答案 0 :(得分:1)

在我看来,您的查询中唯一缺少的是id_shop子句中的GROUP BY

SELECT * FROM `ps_product_lang`
WHERE `link_rewrite`
IN (SELECT `link_rewrite` FROM `ps_product_lang`
GROUP BY `link_rewrite`, `id_lang`, `id_shop`
HAVING COUNT(`link_rewrite`) > 1)

答案 1 :(得分:0)

您声明的要求是“仅当id_shop,id_lang相同时才重复”。这意味着,在某个地方,您的查询需要包含以下内容:

select id_shop, id_lang, count(*) records
from the applicable tables
group by id_shop, id_lang
having count(*) > 1

你必须找到合适的位置。

答案 2 :(得分:0)

在MySQL中执行此操作的最有效方法是使用exists

SELECT *
FROM `ps_product_lang` pl
WHERE exists (select 1 
              from `ps_product_lang` pl2
              where pl2.id_shop = pl.id_shop and
                    pl2.id_lang = pl.id_lang and
                    pl2.id_product <> pl.id_product
             );