左连接请求中的SQLite计数

时间:2014-01-31 20:13:05

标签: sqlite count

我的模型是1个酒可以有很多瓶。这些瓶子的字段为output_type NULL或NOT NULL。

实际上,我可以像这样计算瓶子:

SELECT COUNT(DISTINCT(bottles.id)) AS total_bottles
FROM wines
LEFT JOIN bottles ON wines.id = bottles.wine_id AND bottles.status=1 AND bottles.output_type IS NULL

这很有效。

但现在我需要更多:我想计算存储的瓶子数(output_type NULL)并计算同一请求中的瓶子消失(output_type NOT NULL)。

所以我的LEFT JOIN还不够,因为我无法计算存储的瓶子和主要请求中的瓶子。

我见过这样的事情,包括LEFT JOIN中的“子请求”:

LEFT JOIN (SELECT count(*) AS bottle_stored FROM bottles WHERE bottles.status=1 AND bottles.output_type IS NULL) AS total_stored ON wines.id = bottles.wine_id

但这不起作用。如果这是有效的,我可以复制LEFT JOIN来计算已经过去的瓶子。

编辑: 这里有更多解释。这是我目前的要求。我可以为每种葡萄酒计算所有存储的瓶子(output_type IS NULL)。

SELECT wines.id, wines.winery
COUNT(DISTINCT(bottles.id)) AS total_bottles
FROM wines   
LEFT JOIN bottles ON wines.id = bottles.wine_id AND bottles.status=1 AND bottles.output_type IS NULL 
WHERE wines.status = 1  
GROUP BY wines.id  

编辑2(添加了数据库架构):

wines table
-----------
id (vc)
winery (vc)
name (vc)
status (int)
...

bottles table
-------------
id (vc)
wine_id (vc)
input_type (int)
input_date (datetime)
output_type (int)
output_date (datetime)
status (int)
...

我想:

  • 列出所有葡萄酒
  • 计算列表中每个葡萄酒的存储瓶数(output_type NULL)
  • 为列表中的每个葡萄酒计算瓶子消失(output_type NOT NULL)

在同一请求中。

我的主键和外键是varchar,因为它是UUID(全局同步系统)。

1 个答案:

答案 0 :(得分:3)

试试这个:

SELECT COUNT(DISTINCT(bottles.id)) AS bottles_stored, 
       (SELECT COUNT(DISTINCT(bottles.id)) AS total_bottles
          FROM wines
          LEFT JOIN bottles ON wines.id = bottles.wine_id AND bottles.status = 1) - COUNT(DISTINCT(bottles.id)) AS bottles_gone
  FROM wines
  LEFT JOIN bottles ON wines.id = bottles.wine_id AND bottles.status = 1 AND bottles.output_type IS NULL
  1. 选择存储的所有瓶子=> bottles.output_type = NULL
  2. 计算瓶子总量的子查询
  3. 从total_bottles =>中减去存储的瓶子数量已经消失的瓶子
  4. muqaddar第二次编辑后的更新:

    首先,列出所有葡萄酒的查询(1):

    SELECT w.id,
           w.name,
           w.winery
      FROM wines
    

    接下来,我们统计所有存放的瓶子(2)和瓶子(2)的特定葡萄酒id = 1:

    SELECT COUNT(b.id) 
      FROM bottles AS b 
     WHERE b.output_type IS NULL AND 
           b.wine_id = 1
    

    SELECT COUNT(b.id) 
      FROM bottles AS b 
     WHERE b.output_type IS NOT NULL AND 
           b.wine_id = 1
    

    作为第三步,我们将所有三个查询与查询(2)和(3)组合为子查询,我们用外部查询替换w.id的静态id = 1:

    SELECT w.id,
           w.name,
           w.winery,
           (SELECT COUNT(b.id) 
              FROM bottles AS b 
             WHERE b.output_type IS NULL AND 
                   b.wine_id = w.id) AS bottles_stored,
           (SELECT COUNT(b.id) 
              FROM bottles AS b 
             WHERE b.output_type IS NOT NULL AND 
                   b.wine_id = w.id) AS bottles_gone
      FROM wines