-2

我有一张如下表。

一张用于存放水果的桌子,一张用于存放水果的桌子。

create table fruits(fruit_id int, fruit_name VARCHAR(255));  
create table type(fruit_id int, status VARCHAR(255));

INSERT INTO fruits(fruit_id, fruit_name) 
            values(101, 'Apple'),
                  (102, 'Mango'),
                  (103, 'Lemon'),
                  (104, 'Grape'),
                  (105, 'Orange');

INSERT INTO type(fruit_id, status) 
          values(101, 'Edible');
                (101, 'Sweet'),
                (102, 'Edible'),
                (103, 'Edible'),
                (103, 'Salty'),
                (103, 'Sour'),
                (104, 'Sour');

现在我想要一个如下所示的输出

  Fruit_id    FruitName
    101       Apple
    102       Mango
    103       Lemon
    104       Grape 

我用过INNER JOIN,但苹果、柠檬和葡萄的重复行

SELECT fruits.* 
FROM fruits INNER JOIN type 
ON type.fruit_id = fruits.fruit_id
4

5 回答 5

3

您可以使用DISTINCT忽略这样的重复行:

SELECT DISTINCT F.*
FROM fruits f
INNER JOIN type t ON F.Fruit_id = t.Fruit_id;

看到这个 SQLFiddle

于 2012-09-27T06:59:07.327 回答
2
select f.fruit_id,f.FruitName from 
fruits where fruit_id in(select distinct fruit_id from type)
于 2012-09-27T06:53:18.107 回答
2

像你说的那样写 sql :-)

“告诉我所有存在类型的水果”:

select *
from fruits
where exists (
    select *
    from types 
    where types.fruit_id = fruits.fruit_id
)
于 2012-09-27T06:56:52.663 回答
1
SELECT f.fruit_id ,f.fruit_name 
FROM fruits f 
INNER JOIN type t ON f.fruit_id=t.fruit_id 
GROUP BY f.fruit_id,f.fruit_name

或者

SELECT DISTINCT f.fruit_id ,f.fruit_name 
FROM fruits f 
INNER JOIN type t ON f.fruit_id=t.fruit_id 
于 2012-09-27T06:59:45.420 回答
1

您会得到重复的结果,因为在进行内部连接时,它会为您提供数据之间的对,因此 afruit出现多次是正常的。

对于您所拥有的,也许可以DISTINCT(fruits.*)SELECT语句中使用来解决您的问题。

希望这可以帮助。

于 2012-09-27T07:00:10.587 回答