0

我有 3 张桌子:product,,,order_detailsorders

我想在一个查询中加入他们,显示用户购买的所有产品。

这是我的代码:

SELECT products.id AS id,
      products.kode  AS kode,
      products.sub_kode AS sub_kode,
      products.nama AS nama,
      products.barcode AS barcode,
      products.harga AS harga,
      IFNULL(products.keterangan_kemasan, ' ') AS keterangan_kemasan,
      IFNULL(products.keterangan_ukuran ,' ') AS keterangan_ukuran,
      SUM(IFNULL(order_details.jumlah_pesanan_akhir,0)) AS jumlah,
      IFNULL(order_details.jumlah_pesanan_akhir,0) AS jumlah_beli,
      orders.idmember AS member
    FROM products LEFT JOIN (orders,order_details)
    ON (orders.id = order_details.idorder
      AND order_details.product_kode = products.kode
      AND order_details.product_subkode = products.sub_kode)
    WHERE products.nama LIKE '%asdu%'
      AND IFNULL(orders.idmember, 21376) = 21376     
    GROUP BY products.kode, products.sub_kode
    ORDER BY IFNULL(order_details.jumlah_pesanan_akhir,0) DESC,
      products.nama ASC
    LIMIT 30;

发生的情况是,当客户从不购买该商品时,该商品将不会显示。同时,我希望它们显示出来。

如果我从查询中删除它,

AND IFNULL(orders.idmember, 21376) = 21376     

一切都会很好地展示出来。但它会显示其他人的订单历史。

4

2 回答 2

1

因此,如果我理解,您想要所有看起来像的产品%asdu%,并且您想知道客户21376是否购买了它们。

用户的 id 必须是 LEFT JOIN 子句的一部分,否则将被过滤掉。

SELECT products.id AS id,
      products.kode  AS kode,
      products.sub_kode AS sub_kode,
      products.nama AS nama,
      products.barcode AS barcode,
      products.harga AS harga,
      IFNULL(products.keterangan_kemasan, ' ') AS keterangan_kemasan,
      IFNULL(products.keterangan_ukuran ,' ') AS keterangan_ukuran,
      SUM(IFNULL(order_details.jumlah_pesanan_akhir,0)) AS jumlah,
      IFNULL(order_details.jumlah_pesanan_akhir,0) AS jumlah_beli,
      orders.idmember AS member
    FROM products 
        LEFT JOIN order_details
            ON order_details.product_kode = products.kode
            AND order_details.product_subkode = products.sub_kode
        LEFT JOIN orders
            ON orders.id = order_details.idorder
            AND orders.idmember = 21376
    WHERE products.nama LIKE '%asdu%'
    GROUP BY products.kode, products.sub_kode
    ORDER BY IFNULL(order_details.jumlah_pesanan_akhir,0) DESC,
      products.nama ASC
    LIMIT 30;

我已经重写了连接,以明确什么是连接什么。

于 2013-10-10T09:50:28.513 回答
0

我建议您重新考虑将其限制为 1 个查询的必要性。正如你所注意到的,很难让它做你想做的事。

两个或三个查询更容易理解。你现在正在努力,如果你一年后回顾一下,这看起来会很乱。此外,如果其他人需要纠正这一点,他们将很难过。

我的建议:

SELECT * FROM users WHERE id=123
    // With that result:
    SELECT * FROM orders WHERE user_id=$user['id']
        // While this loops:
        SELECT * FROM order_details WHERE orderid=$orders['id']

数据库甚至可能更快,连接很慢,尤其是对于大表。它将锁定表,这会使其他用户变慢。而且GROUP BY's 也无济于事

于 2013-10-10T09:53:29.323 回答