mysql“IN”子句问题
我有两张像下面这样的桌子mysql“IN”子句问题,mysql,sql,Mysql,Sql,我有两张像下面这样的桌子 Table Apple: ---------------------------------------- id | type | ---------------------------------------- 1 | 3 | ---------------------------------------- 2 |
Table Apple:
----------------------------------------
id | type |
----------------------------------------
1 | 3 |
----------------------------------------
2 | 3 |
----------------------------------------
3 | 3 |
----------------------------------------
Table Orange:
-------------------------------------------
orange id | apple id |
-------------------------------------------
1 | 1 |
-------------------------------------------
2 | 2 |
-------------------------------------------
3 | 3 |
-------------------------------------------
4 | 1 |
--------------------------------------------
4 | 2 |
--------------------------------------------
4 | 3 |
--------------------------------------------
SELECT orange_id
FROM orange
WHERE apple_id IN (SELECT id
FROM apple
WHERE type = 3);
我的问题如下:
Table Apple:
----------------------------------------
id | type |
----------------------------------------
1 | 3 |
----------------------------------------
2 | 3 |
----------------------------------------
3 | 3 |
----------------------------------------
Table Orange:
-------------------------------------------
orange id | apple id |
-------------------------------------------
1 | 1 |
-------------------------------------------
2 | 2 |
-------------------------------------------
3 | 3 |
-------------------------------------------
4 | 1 |
--------------------------------------------
4 | 2 |
--------------------------------------------
4 | 3 |
--------------------------------------------
SELECT orange_id
FROM orange
WHERE apple_id IN (SELECT id
FROM apple
WHERE type = 3);
上述查询将返回以下结果集
1,2,3
但我需要1,2,3,4。我的问题出在哪里了。?请帮帮我 为什么不改用连接呢?这个查询看起来很难看,而且没有经过优化,但我仍然不知道为什么它不起作用。使用与此类似的联接
select orange_id from Orange
inner join Apple on Apple.id = Orange.apple_id
where Apple.type = 3
希望能有帮助
Leo如果表变得更大,那么这不是一种很好的查询方式。您确定结果吗?def应该返回6行…使用此数据,您的查询应该返回1,2,3,4,4,4对我有效:尝试使用select distinct orange_id from orange where apple_id in select id from apple where type=3;为了得到1,2,3,4我很抱歉伙计们。对不起,浪费了你的时间。这是我粗心的错误。但是我从Leo那里得到了一个优化的代码。谢谢你,利奥。