繁体   English   中英

一对多加入,但只有第一行

[英]One to many join but only the first row

我需要通过ID加入2个表,而不会获取ID,InfoA和InfoB的重复值。 我不需要InfoB2列中的数据。 当我加入ID上的表,因为它是一个1到多个连接,我最终得到重复的值,并希望摆脱它们。 我只想要没有重复项的ID,InfoA和InfoB。 有任何想法吗?

示例:TableA:

| ID      |   InfoA  |
|   1     |   animals|
|   2     |   plants |

表B:

|     ID  |   InfoB  | InfoB2   |
|   1     |   A      |   X      |
|   1     |   A      |   Y      |
|   1     |   A      |   Z      |
|   2     |   B      |   X      |
|   2     |   B      |   Y      |
|   2     |   B      |   Z      |

做一个普通的连接,因为它是1到多,我得到这个,但不想要重复。 我不想要这个:

|     ID  |   InfoB  |  InfoB   |
|   1     |   animals|   A      |
|   1     |   animals|   A      |
|   1     |   animals|   A      |
|   2     |   plants |   B      |
|   2     |   plants |   B      |
|   2     |   plants |   B      |

我的目标是得到这个(注意我不需要列InfoB2):

|     ID  |   InfoA  |   InfoB  |
|   1     |   animals|   A      |
|   2     |   plants |   B      |

您可以使用distinct关键字:

SELECT DISTINCT a.id, infoa, infob
FROM   tablea a
JOIN   tableb b ON a.id = b.id

最快的方法可能是:

select a.*,
       (select b.infob from tableb b on a.id = b.id limit 1)
from tablea a;

为了提高性能,你需要tableb(id, infob)上的索引tableb(id, infob)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM