从2个表中加入字段

时间:2012-12-31 03:08:32

标签: mysql join

我有两张桌子:

table 'g'
+------+
| id   |
+------+
|    1 |
|   32 |
|    3 |
|    6 |
|    5 |
|   22 |
|   54 |
|   21 |
+------+

table 'h'
+------+------+
| id   | sl   |
+------+------+
|    1 |  323 |
|   11 |  423 |
|    1 |  333 |
|   33 |   32 |
|   44 |  443 |
+------+------+

如何显示来自2个表格的记录(从'g'和'h'表中选择不同的id并从'h'表中为每个id加入最大'sl'。'id'表示'g'表与表'h'的'id'不匹配,那些'sl'字段将为null)

+------+------+
| id   | sl   |
+------+------+
|    1 |  333 |
|   32 | null |
|    3 | null |
|    6 | null |
|    5 | null |
|   22 | null |
|   54 | null |
|   21 | null |
|   11 |  423 |
|   33 |   32 |
|   44 |  443 |
+------+------+

-Thanks。

1 个答案:

答案 0 :(得分:2)

这可以通过两者之间的UNION完成,左边作为派生表加入h以获取MAX()值:

SELECT
  allids.id,
  MAX(sl) AS sl
FROM
  /* Subquery gets UNION (distinct, not UNION ALL) of ids from both tables */
  (SELECT id FROM g UNION SELECT id FROM h) allids
  /* LEFT JOINed back against `h` for the MAX() aggregates */
  LEFT JOIN h ON allids.id = h.id
GROUP BY id

http://sqlfiddle.com/#!2/2c348/3

评论后更新:

要强制它们按照插入它们的任意(无序)顺序进行排序,可能需要将一个数字文本放入子查询中,该子查询将在ORDER BY中使用。

但是插入的订单行对RDBMS并没有多大意义。如果没有ORDER BY条款,您无法可靠地假设它们将以相同的顺序返还给您。

SELECT
  allids.id,
  MAX(sl) AS sl
FROM
  /* Awful hack adds a number literal which is used in the ORDER BY */
  /* This still won't guarantee that the rows from each table will be in the original order though */
  (SELECT id, 1 AS sort FROM g UNION SELECT id, 2 AS sort FROM h) allids
  LEFT JOIN h ON allids.id = h.id
GROUP BY id
ORDER BY sort

http://sqlfiddle.com/#!2/2c348/6