具有无效关系错误的SQL嵌套查询(ORA-00920错误)

时间:2014-05-13 13:56:52

标签: sql oracle

我总共3 tables。我试图选择成本食品的价格必须是最高的,类别名称必须属于有机食品。

我提出了以下SQL QUERY,但我收到了无效的关系错误。

有人可以指出问题可能是什么吗?

由于

SELECT PRICE, LABEL
FROM FOOD
WHERE FOOD.FOOD_ID = (
    SELECT FOOD_ID
    FROM FOOD_CATEGORY
    WHERE FOOD_CATEGORY.FOOD_ID = (
       SELECT FOOD_ID
       FROM CATEGORY
       WHERE NAME = 'ORGANIC'
    )
);

食物

  • FOOD_ID
  • LABEL
  • PRICE

FOOD_CATEGORY

  • FOOD_ID
  • CATEGORY_ID

CATEGORY

  • CATEGORY_ID
  • NAME

关系

FOOD.FOOD_ID = FOOD_CATEGORY.FOODID 

FOOD_CATEGORY.CATEGORYID = CATEGORY.CATEGORYID

2 个答案:

答案 0 :(得分:4)

我怀疑你有更多的食物属于“有机”类别。否则就不需要表FOOD_CATEGORY。表FOOD_CATEGORY用于创建多对多关系。

为什么不呢:

SELECT PRICE, LABEL
FROM FOOD
JOIN FOOD_CATEGORY ON (FOOD_CATEGORY.FOOD_ID = FOOD.FOOD_ID)
JOIN CATEGORY ON (CATEGORY.CATEGORY_ID = FOOD_CATEGORY.CATEGORY_ID)
WHERE CATEGORY.NAME = 'ORGANIC';

或使用IN而不是=

SELECT PRICE, LABEL
FROM FOOD
WHERE FOOD.FOOD_ID IN (
    SELECT FOOD_ID
    FROM FOOD_CATEGORY
    WHERE FOOD_CATEGORY.CATEGORY_ID = (
       SELECT CATEGORY_ID
       FROM CATEGORY
       WHERE NAME = 'ORGANIC'
    )
);

答案 1 :(得分:0)

因为CATEGORY_ID代替FOOD_ID

SELECT PRICE, LABEL
FROM FOOD
WHERE FOOD.FOOD_ID = (
    SELECT FOOD_ID
    FROM FOOD_CATEGORY
    WHERE FOOD_CATEGORY.FOOD_ID = (
       SELECT CATEGORY_ID
       FROM CATEGORY
       WHERE NAME = 'ORGANIC'
    )
);