0

我有一张桌子locations和一张桌子stockLevels。我正在处理一个复杂的查询,以一次性告诉我哪些物品已经存货很长时间,它们在哪个位置以及其他一些东西。

部分原因是给我不准确的结果。

... LEFT JOIN ...
SELECT id, sum(stockLevel) as totalStockLevel FROM stockLevels 
    WHERE stockLocation IN 
        ((SELECT 
            GROUP_CONCAT(CONVERT(id, CHAR(8))) as idList 
            FROM `locations` WHERE  `isThirdParty`  = '0' 
            AND `pickFrom`='1' 
        GROUP BY pickFrom)) 
    GROUP BY id) 
ourStock ON ourStock.id=products.id
... MORE OF QUERY ....

这是整个查询的一个片段,内部SELECT独立工作,但它没有将 ID 列表应用到 IN 子句中,似乎只是读取了第一个。

所以,解释得更清楚。

内部SELECT

SELECT 
    GROUP_CONCAT(CONVERT(id, CHAR(8))) as idList 
    FROM `locations` WHERE  `isThirdParty`  = '0' 
    AND `pickFrom`='1' 
GROUP BY pickFrom

将逗号分隔的列表值作为名为 的列返回idList,该值是1,2,10,11

此查询有效。

如果我在原始查询中手动使用逗号分隔列表,它也可以工作,即:

... LEFT JOIN ...
SELECT id, sum(stockLevel) as totalStockLevel FROM stockLevels 
    WHERE stockLocation IN 
        (1,2,10,11) 
    GROUP BY id) 
ourStock ON ourStock.id=products.id
... MORE OF QUERY ....

此代码不会产生任何错误,但它产生的结果就是这个查询的结果:

... LEFT JOIN ...
SELECT id, sum(stockLevel) as totalStockLevel FROM stockLevels 
    WHERE stockLocation IN 
        (1) 
    GROUP BY id) 
ourStock ON ourStock.id=products.id
... MORE OF QUERY ....

因此,我没有将由内部查询生成的逗号分隔列表注入到外部查询的 IN 子句中。

谁能告诉我为什么?

4

1 回答 1

0

IN()需要一个值列表或一个子查询,但你给它一个 varchar。您可能会尝试加入 stockLocation 和 Locations 以产生所需的结果:

SELECT stockLevels.id, 
       sum(stockLevels.stockLevel) as totalStockLevel 
  FROM stockLevels 
 INNER JOIN locations
    ON stockLevels.stockLocation = locations.id
   AND locations.isThirdParty = '0'
   AND locations.pickFrom = '1'
 GROUP BY stockLevels.id

当然,您可以消除 group_concat 以获得相同的效果:

WHERE stockLocation IN 
    (SELECT id
       FROM `locations` 
      WHERE `isThirdParty` = '0' 
        AND `pickFrom`='1' 
    )
于 2012-07-30T12:34:20.270 回答