mySQL 联接三个表 - 电子商务项目、浏览量和销售额

mySQL JOIN three tables - Ecommerce items , views and sales

我正在使用 php mySql 构建电子商务系统,但我不知道如何 LEFT JOIN 三个表。

我需要所有商店商品的列表,添加每个商品的浏览量和销售额

            TABLE #1 - store_sales
            ---------------
            itemID | date
            --------------

            TABLE #2 - store_views
            --------------
            itemID | date
            --------------

            TABLE #3 - store_items 
            ---------------------------------
            itemID | itemName 
            ---------------------------------

            RESULT
            -----------------------
            itemID | itemName | COUNT(store_sales) | COUNT(store_views)


            EXAMPLE:
            -----------------------
            itemID | itemName | COUNT(store_sales) | COUNT(store_views) 
            1         PHONE             3                   45 
            2         BOOK              5                   61

我的代码有错误:

            SELECT
            a.itemID    ,
            b.itemID    ,
            c.itemID    ,
            COUNT(if(a.itemID   = c.itemID  , a.itemID  , NULL)) AS views       ,
            COUNT(if(b.itemID   = c.itemID  , b.itemID  , NULL)) AS sales               

            FROM store_views a

            LEFT JOIN store_sales b
            ON a.itemID = b.itemID 

            LEFT JOIN store_items c
            ON a.itemID = c.itemID

            WHERE 1=1
            GROUP BY itemID 

您可以在子选择中分别获取销售和观看次数的计数,然后对您的项目进行左连接 table,使用 COALESCE 跳过计数的空记录

SELECT
a.itemID ,
COALESCE(b.item_sales,0),
COALESCE(c.item_views,0)
FROM  store_items a
LEFT JOIN (
    SELECT itemID,COUNT(*) as item_sales
    FROM store_sales
    GROUP BY itemID  
) b ON a.itemID = b.itemID 
LEFT JOIN (
    SELECT itemID,COUNT(*) as item_views
    FROM store_views v
    GROUP BY itemID
) c ON a.itemID = c.itemID