1

我正在使用 mysql,我有三个表 T1、T2、T3,它们包含如下数据:

+-------+
| t1.id |
+-------+
| 1    |
| 2    |
| 3    |
| 4    |
| 5    |
+------+

+-------+
| t2.id |
+-------+
| 1    |
| 2    |
| 3    |
| 4    |
+-------+

+-------+
| t3.id |
+-------+
| 1    |
| 2    |
| 3    |
+-------+

    I want to be able to select data as follows:

id      t1.id   t2.id   t3.id
1       1       1       1
2       2       2       2
3       3       3       3
4       4       4       null
5       5       null    null

我怎样才能做到这一点?

4

3 回答 3

2

假设您打算T1用作 base id,一对LEFT JOINs 将为您提供所需的结果:

SELECT 
  /* base id */
  T1.id AS id,
  /* Redundant t1.id */
  T1.id AS t1_id,
  T2.id AS t2_id,
  T3.id AS t3_id
FROM
  T1
  LEFT JOIN T2 ON T1.id = T2.id
  LEFT JOIN T3 ON T1.id = T3.id

请注意,这会冗余使用T1.id,但这正是您在建议的输出中所拥有的,所以我在这里复制了它。

如果您真正想要的是从所有表中获取所有可能的 id,请使用 aUNION来加入。这会将三个表中不同的 id 集组合成一个子查询allids,用作LEFT JOIN其他三个表中每个表的基本 id。如果一个特定的 id 存在T2 T1存在,它仍然会出现在输出中。

SELECT 
  allids.id AS id,
  T1.id AS t1_id,
  T2.id AS t2_id,
  T3.id AS t3_id
FROM
  ( SELECT id FROM T1 UNION SELECT id FROM T2 UNION SELECT id FROM T3 ORDER BY id) allids
  LEFT JOIN T1 ON allids.id = T1.id
  LEFT JOIN T2 ON allids.id = T2.id
  LEFT JOIN T3 ON allids.id = T3.id
于 2012-08-16T14:26:45.147 回答
0
SELECT t1.id, t2.id, t3.id
FROM t1 
LEFT JOIN t2 ON t1.id=t2.id
LEFT JOIN t3 ON t1.id=t3.id

工作,如果t1保证有一个严格的所有ID超集。

如果没有,您将需要一个辅助表:

SELECT th.id,t1.id, t2.id, t3.id
FROM (
  SELECT id FROM t1
  UNION DISTINCT 
  SELECT id FROM t2
  UNION DISTINCT 
  SELECT id FROM t3
) AS th
LEFT JOIN t1 ON th.id=t1.id
LEFT JOIN t2 ON th.id=t2.id
LEFT JOIN t3 ON th.id=t3.id
于 2012-08-16T14:28:28.297 回答
0

我认为您想要的解决方案涉及完全外部联接:

SELECT coalesce(t1.id, t2.id, t3.id) as id,
       T1.id as t1_id, T2.id as t2_id, T3.id as t3_id
FROM T1 full outer JOIN
     T2 ON T2.id = T1.id full outer JOIN
     T3 ON T3.id = coalesce(t1.id, t2.id)

我建议使用完整的外连接,以防其他两个表中的 id 不在 T1 中。您没有指定 t1 是驱动表。

于 2012-08-16T14:32:27.827 回答