SQL 运行 嵌套查询时浏览器崩溃

SQL Browser Crashing when running a Nested Query

我有一个包含三个表的数据库:

  1. 杂货店
  2. 营养
  3. grocery_nutrient(多对多)

实际上,数据库非常大,我遇到了 运行 宁这个查询的问题,SQL 浏览器在我 运行 时崩溃,如果我添加 LIMIT 它有效.

这是我为其编写的查询。

SELECT 
  grocery.*, 
  (
    SELECT 
      grocery_nutrient.amount || " " || grocery_nutrient.unit 
    FROM 
      grocery_nutrient 
    WHERE 
      grocery_nutrient.nutrient_id = 2 
      AND grocery.grocery_id = grocery_nutrient.grocery_id
  ) AS calories, 
  (
    SELECT 
      grocery_nutrient.amount || " " || grocery_nutrient.unit 
    FROM 
      grocery_nutrient 
    WHERE 
      grocery_nutrient.nutrient_id = 6 
      AND grocery.grocery_id = grocery_nutrient.grocery_id
  ) AS fats, 
  (
    SELECT 
      grocery_nutrient.amount || " " || grocery_nutrient.unit 
    FROM 
      grocery_nutrient 
    WHERE 
      grocery_nutrient.nutrient_id = 3 
      AND grocery.grocery_id = grocery_nutrient.grocery_id
  ) AS protein, 
  (
    SELECT 
      grocery_nutrient.amount || " " || grocery_nutrient.unit 
    FROM 
      grocery_nutrient 
    WHERE 
      grocery_nutrient.nutrient_id = 4 
      AND grocery.grocery_id = grocery_nutrient.grocery_id
  ) AS carbs 
FROM 
  grocery 
  LEFT JOIN grocery_nutrient ON grocery.grocery_id = grocery_nutrient.grocery_id
GROUP BY 
  grocery.grocery_id

如果使用条件聚合,可以简化查询:

SELECT g.*, 
       MAX(CASE WHEN n.nutrient_id = 2 THEN n.amount || ' ' || n.unit END) AS calories, 
       MAX(CASE WHEN n.nutrient_id = 6 THEN n.amount || ' ' || n.unit END) AS fats, 
       MAX(CASE WHEN n.nutrient_id = 3 THEN n.amount || ' ' || n.unit END) AS protein, 
       MAX(CASE WHEN n.nutrient_id = 4 THEN n.amount || ' ' || n.unit END) AS carbs
FROM grocery g LEFT JOIN grocery_nutrient n 
ON g.grocery_id = n.grocery_id
GROUP BY g.grocery_id