[英]One to many join but only the first row
I have 2 tables that I need to join via ID without getting the duplicate values For ID, InfoA, and InfoB. 我需要通过ID加入2个表,而不会获取ID,InfoA和InfoB的重复值。 I do not need the data in column InfoB2. 我不需要InfoB2列中的数据。 When I join the table on ID because it is a 1 to many join I end up with duplicate values and want to get rid of those. 当我加入ID上的表,因为它是一个1到多个连接,我最终得到重复的值,并希望摆脱它们。 I only want ID, InfoA, and InfoB without the duplicates. 我只想要没有重复项的ID,InfoA和InfoB。 Any ideas? 有任何想法吗?
Example: TableA: 示例:TableA:
| ID | InfoA |
| 1 | animals|
| 2 | plants |
TableB: 表B:
| ID | InfoB | InfoB2 |
| 1 | A | X |
| 1 | A | Y |
| 1 | A | Z |
| 2 | B | X |
| 2 | B | Y |
| 2 | B | Z |
Doing a normal join, because it is 1 to many I get this but do not want the duplicates. 做一个普通的连接,因为它是1到多,我得到这个,但不想要重复。 I don't want this: 我不想要这个:
| ID | InfoB | InfoB |
| 1 | animals| A |
| 1 | animals| A |
| 1 | animals| A |
| 2 | plants | B |
| 2 | plants | B |
| 2 | plants | B |
My goal is to get this (note I do not need column InfoB2): 我的目标是得到这个(注意我不需要列InfoB2):
| ID | InfoA | InfoB |
| 1 | animals| A |
| 2 | plants | B |
You could use the distinct
keyword: 您可以使用distinct
关键字:
SELECT DISTINCT a.id, infoa, infob
FROM tablea a
JOIN tableb b ON a.id = b.id
The fastest way is likely to be: 最快的方法可能是:
select a.*,
(select b.infob from tableb b on a.id = b.id limit 1)
from tablea a;
For performance, you would want an index on tableb(id, infob)
. 为了提高性能,你需要tableb(id, infob)
上的索引tableb(id, infob)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.