2011-12-13 53 views
0

我有三個表:MYSQL - 查找重複交叉關係表

`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` 

任何人有什麼想法?

+0

「敢肯定它不工作」,會發生什麼? – Marcus 2011-12-13 23:56:56

+0

@Marcus我得到的結果似乎非常關閉爲許多網站報告60重複的東西,我99%肯定是假的 – 2011-12-14 00:23:45

回答

1

我不知道這是不是你要找的。也許有一些示例數據可以改進我的查詢。有了這個你把所有產品的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`