0

我有 2 张桌子:

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,并为每个 id 从“h”表中加入最大“sl”。“g”表的“id”不匹配表“h”的“id”,那些“sl”字段将为空)

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

-谢谢。

4

1 回答 1

2

这可以通过UNION两者之间的 a 来完成,作为派生表左连接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

于 2012-12-31T03:11:33.310 回答