MySQl - 查找重复的跨关系表

时间:2011-12-13 23:53:46

标签: mysql sql

我有三张桌子:

`products`
----------
`product_id` (int)
`sku` (varchar=50)

`websites`
----------
`website_id` (int)

`website_products`
----------
`website_id` (int)
`product_id` (int)

我正在尝试根据每个网站的SKU 找到重复产品。这是我到目前为止的尝试,但很确定它不起作用:

SELECT b.`website_id`, a.`product_id` ,COUNT(a.*) AS count
FROM `products` AS a 
     LEFT JOIN `website_products` AS b 
         ON ( a.`product_id` = b.`product_id` ) 
WHERE 1
GROUP BY a.`sku` 
HAVING count > 1
ORDER BY b.`website_id`

有人有任何想法吗?

1 个答案:

答案 0 :(得分:1)

我不知道这是不是你要找的。也许有一些示例数据,我可以优化我的查询。通过这种方式,您可以将所有产品用于网站中的SKU(适用于具有多种产品的SKU)

SELECT 
    b.`website_id`, a.sku, 
    group_concat(DISTINCT a.`product_id`) as sku_products 
FROM `products` AS a 
     LEFT JOIN `website_products` AS b 
         ON ( a.`product_id` = b.`product_id` ) 
GROUP BY b.`website_id`, a.`sku` 
HAVING count(distinct a.`product_id` ) > 1
ORDER BY b.`website_id`