我正在做一個查詢以返回存儲在sb_carts表中的所有用戶購物車。存儲在sb_carts中的產品信息通過兩個關鍵字product_sku和school_id引用。它需要參考兩個返回唯一的產品與獨特的庫存水平等MYSQL內部通過兩個鍵加入兩個表
當我執行下面的查詢它返回一行,我期待3行。 我已經嘗試將內部連接分解爲兩個單獨的連接,但這仍然只返回1個結果。僅加入一個密鑰就能獲得理想的結果,但可能會重新調整錯誤的產品。左聯接返回3行,但某些數據丟失特定產品
下面是我在做什麼
SELECT sb_carts.product_sku FROM sb_carts INNER JOIN sb_products ON sb_products.sku = sb_carts.product_sku AND sb_products.school_id = sb_carts.school_id WHERE sb_carts.order_id = 0 AND sb_carts.user_id = 2 GROUP BY sb_carts.cart_id
完整的查詢看起來簡單的例子像
SELECT COUNT(DISTINCT sb_carts.cart_id) as quantity, sb_carts.* FROM sb_carts INNER JOIN sb_children ON sb_children.child_id = sb_carts.child_id INNER JOIN sb_school_entities ON sb_school_entities.school_id = sb_children.school_id INNER JOIN sb_products ON sb_products.sku = sb_carts.product_sku AND sb_products.school_id = sb_carts.school_id LEFT JOIN sb_houses ON sb_children.house_id = sb_houses.id LEFT JOIN sb_refund_cart ON sb_carts.cart_id = sb_refund_cart.cart_id WHERE sb_carts.order_id = 0 AND sb_carts.user_id = 2 GROUP BY sb_carts.child_id, sb_carts.product_sku, sb_carts.school_id ORDER BY sb_children.dob_year, sb_children.dob_month, sb_children.dob_day ASC
是的,情況正是如此。如果您使用GROUP BY,MySQL不會強制您使用聚合函數(例如,與MS-SQL不同,例如,該查詢無效) –