我试图计算活跃销售订单中的库存数量,这些订单存储在xcart_order_details中。我还想只计算x天内订单中的库存,这些订单的状态为已处理过的' P'或排队' Q'以及股票类型是否与某些地点匹配; C1库存,C2库存等。
在旧的xcart数据库中,这曾经相对简单;
SELECT COUNT(`amount`)
FROM `xcart_order_details`
WHERE `productid` IN (
SELECT `productid`
FROM `xcart_products` WHERE `orderid` IN
(SELECT `orderid`
FROM `xcart_orders`
WHERE `date` > ".$date_range."
AND (`status` = 'P'
OR `status` = 'Q'))
AND (LOWER(param01) = 'c1 stock'
OR LOWER(param01) = 'c2 stock'
OR LOWER(param01) = 'g stock'
OR LOWER(param01) = 'stock')
AND `productid` = ".$safe_prodid.")
此查询有效。但现在我们的库存位置存储在另一个名为xcart_extra_field_values的表中,并且必须在fieldid = 5的情况下检索;
我尝试使用联接从xcart_extra_field_values获取其中fieldid = 5的值字段,并尝试执行我在上面的查询中执行的操作,但它不起作用。
SELECT COUNT(`a.amount`)
FROM xcart_order_details a,
xcart_extra_field_values b
WHERE a.productid IN (
SELECT productid
FROM xcart_products WHERE orderid IN
(SELECT orderid
FROM xcart_orders
WHERE date > 1409529600
AND (status = 'P'
OR status = 'Q'))
AND (LOWER(b.value) = 'c1 stock'
OR LOWER(b.value) = 'c2 stock'
OR LOWER(b.value) = 'g stock'
OR LOWER(b.value) = 'stock')
AND (a.productid = b.productid)
AND (a.productid = 4169)
AND (b.fieldid = 5)
不幸的是,这个查询不起作用,我知道这是一个语法问题,但我得到的错误无济于事。
任何人都可以解释我做错了什么吗?
答案 0 :(得分:0)
您缺少如何加入这两个表的条件。假设表xcart_extra_field_values中有一个xcart_order_details_id,然后使用它。
毕竟,你甚至不必加入。您需要xcart_order_details的结果,其中某些详细信息值记录为EXIST:
SELECT COUNT(`amount`)
FROM `xcart_order_details`
WHERE `productid` IN
(
SELECT `productid`
FROM `xcart_products`
WHERE `orderid` IN
(
SELECT `orderid`
FROM `xcart_orders`
WHERE `date` > ".$date_range."
AND `status` IN ('P','Q')
)
AND `productid` = ".$safe_prodid."
AND EXISTS
(
SELECT *
FROM xcart_extra_field_values v
WHERE v.xcart_order_details_id = xcart_order_details.id
AND fieldid = 5
AND LOWER(param01) IN ('c1 stock','c2 stock','g stock','stock')
);
顺便说一句:你算一下有多少订单明细记录?
答案 1 :(得分:0)
解决。
SELECT COUNT(a.amount)
FROM xcart_order_details a,
xcart_extra_field_values b
WHERE a.productid IN
(SELECT productid
FROM xcart_products
WHERE orderid IN
(SELECT orderid
FROM xcart_orders
WHERE date > 1409529600
AND (status = 'P'
OR status = 'Q'))
AND (LOWER(b.value) = 'c1 stock'
OR LOWER(b.value) = 'c2 stock'
OR LOWER(b.value) = 'g stock'
OR LOWER(b.value) = 'stock'))
AND (a.productid = b.productid)
AND (a.productid = 4169)
AND (b.fieldid = 5)
首先,我在查询结束时错过了一个括号,因为我正在嵌套两个IN查询,我需要在COUNT中删除a.amount
周围的Grave重音,这是不喜欢的。当我并排查看我的查询时,我只注意到了缺失的括号。
编辑:在我的嵌套IN子句之外移动我的连接,因为它嵌套是没有意义的。