我有3个表:product
,order_details
,orders
。
我想在一个查询中加入他们,显示用户购买的所有产品。
这是我的代码:
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
一切都会很好。但它会向其他人展示订单历史。
答案 0 :(得分: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;
我已经重写了联接,以明确什么是加入什么。
答案 1 :(得分: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
也没有帮助