Mysql join为小型解决方案集生成巨大的结果表

时间:2012-05-08 17:55:59

标签: mysql join

我有两个表,我试图选择那些表之间的公共字段完全匹配的行,但是它证明难以编写查询。这是一个简化版本:

表格如下(简化):

T1:
  id, name, sn

T2:
  id, location, sn

我试图将t1.name和t2.loc放在一起,只有t1.sn = t2.sn。 sn字段在两者中都是唯一的,因此最多只有1条记录在表之间匹配。在t1中,所有记录都具有sn字段值,但是在t2中,大约30%的记录具有sn的NULL。所以,我期望连接产生的行数比t1少。

我该如何加入?

感谢。

示例数据:

t1:
+---+--------+-------+-----+
| id| name   | sn    | ... |
+---+--------+-------+-----+
| 1 | thing1 | 12345 |     |
| 2 | thing2 | 10000 |     |
| 3 | thing3 | 33445 |     |
| 4 | thing4 | 99223 |     |
+---+--------+-------+-----+

T2:
+----+--------+-------+-----+
| id | loc    | sn    | ... |
+----+--------+-------+-----+
| 90 | here   | 12345 |     |
| 92 | there  | NULL  |     |
| 96 | near   | 33445 |     |
| 99 | far    | 99223 |     |
+----+--------+-------+-----+

Result:
+--------+-------+-------+
| name   | loc   | sn    |
+--------+-------+-------+
| thing1 | here  | 12345 |
| thing3 | near  | 33445 |
| thing4 | far   | 99223 |
+--------+-------+-------+

1 个答案:

答案 0 :(得分:1)

SELECT
  t1.name AS name,
  t2.loc AS loc,
  t1.sn AS sn
FROM t1
INNER JOIN t2 ON t1.sn=t2.sn