我正在进行查询以返回存储在sb_carts表中的所有用户购物车。存储在sb_carts中的产品信息通过两个键product_sku和school_id引用。它需要引用两者来返回具有独特库存水平的独特产品等。
当我执行以下查询时,它返回一行,我期待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
答案 0 :(得分:1)
问题很可能是GROUP BY
。即使购物车中有多个产品,每个购物车ID也只会返回一条记录。为了得到你想要的,试试这个:
SELECT sb_carts.cart_id, 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 ORDER BY sb_carts.cart_id
这将返回两列(购物车ID和SKU)而不是一列,并且一个购物车ID的所有商品将在查询中显示为连续的行。
答案 1 :(得分:1)
为什么使用Group By
声明?如果您未使用Select
Sum
中的某个功能,AVG
,Group By
等对您的porpouse毫无意义。
因此,尝试运行不带{{1}}语句的查询: - )
希望它有所帮助!
桑蒂! :-)
答案 2 :(得分:0)
多个键上的Mysql INNER JOIN:
SELECT * from table1 as t1
INNER JOIN table2 as t2
ON CONCAT(t1.key1, t2.key2)=CONCAT(t2.key1, t2.key2);
我们在这里做的是组合两个键的值,使它看起来像是一把钥匙。