【发布时间】:2020-08-04 14:00:22
【问题描述】:
我是数据库的初学者。 如果我有这个记录:
tbl_task
|-----------|
| task_id |
|-----------|
| 1234 |
tbl_item1
|-----------|-----------|
| task_id | col_a |
|-----------|-----------|
| 1234 | x |
|-----------|-----------|
| 1234 | y |
tbl_item2
|-----------|-----------|
| task_id | col_a |
|-----------|-----------|
| 1234 | x |
|-----------|-----------|
| 1234 | y |
到目前为止,我的查询只是一个普通的左连接:
SELECT a.task_id, e.col_a as cola1, e2.col_a as cola2
FROM tbl_task a
LEFT OUTER JOIN tbl_item1 e ON a.task_id = e.task_id
LEFT OUTER JOIN tbl_item2 e2 ON a.task_id = e2.task_id
它会产生这样的重复数据:
|-----------|-----------|-----------|
| task_id | cola1 | cola2 |
|-----------|-----------|-----------|
| 1234 | x | x |
|-----------|-----------|-----------|
| 1234 | x | y |
|-----------|-----------|-----------|
| 1234 | y | x |
|-----------|-----------|-----------|
| 1234 | y | y |
如何实现 tbl_item1 / tbl_item2 并不真正关心第一个 tbl 上的哪个记录与另一个匹配的非重复记录?像这样:
|-----------|-----------|-----------|
| task_id | cola1 | cola2 |
|-----------|-----------|-----------|
| 1234 | x | y | <------- here cola 2 could be x / y and it doesn't matter
|-----------|-----------|-----------|
| 1234 | y | x | <------- and here cola2 could be the value other than the data above it.
任何回复都会被欣赏:)。 谢谢。
更新: 也有可能其他数据填充 tbl_item1 但不在 tbl_item2 中。所以我需要的最终结果是:
|-----------|-----------|-----------|
| task_id | cola1 | cola2 |
|-----------|-----------|-----------|
| 1234 | x | x |
|-----------|-----------|-----------|
| 1234 | y | y |
|-----------|-----------|-----------|
| 1234 | z | null |
|-----------|-----------|-----------|
【问题讨论】:
标签: sql database postgresql join outer-join