Mysql:扩展包含原始表中缺失记录的选择

Mysql:扩展包含原始表中缺失记录的选择,mysql,union,Mysql,Union,我有一个包含四个元素的表 | item_id | description | ... | ... | |---------|-------------|-----|-----| | 1 | foo | ... | ... | | 2 | bar | ... | ... | | 3 | biz | ... | ... | | 4 | boo | ... | ... | 还有一个选择查询

我有一个包含四个元素的表

| item_id | description | ... | ... |
|---------|-------------|-----|-----|
|       1 | foo         | ... | ... |
|       2 | bar         | ... | ... |
|       3 | biz         | ... | ... |
|       4 | boo         | ... | ... |
还有一个选择查询,我们称之为查询,它返回如下内容:

| item_id | inventory |
|---------|-----------|
|       2 |        123|        
|       3 |        456|
inventory不是items表的字段,而是查询中的一些计算结果

如示例所示,并非项中的所有记录都返回(这是预期的)

我想“扩展”选择,包括项目中的所有缺失记录,其id库存设置为0

像这样

| item_id | inventory |
|---------|-----------|
|       2 |        123|        
|       3 |        456|
|       1 |          0|        
|       4 |          0|
| item_id | inventory |
|---------|-----------|
|       2 |        123|        
|       3 |        456|
|       1 |          0|        
|       2 |          0|
|       3 |          0|        
|       4 |          0|
我试过了

SELECT    #### "the query" here ####
UNION
SELECT `item_id`, 0 AS `inventory` from `items`
但我有重复的项目

像这样

| item_id | inventory |
|---------|-----------|
|       2 |        123|        
|       3 |        456|
|       1 |          0|        
|       4 |          0|
| item_id | inventory |
|---------|-----------|
|       2 |        123|        
|       3 |        456|
|       1 |          0|        
|       2 |          0|
|       3 |          0|        
|       4 |          0|

我正在寻找一种不修改查询的方法,而只是“扩展”选择。

您正在寻找一个
左外连接

SELECT i.item_id, coalesce(q.inventory, 0) as inventory
from items i left outer join
     (   #### "the query" here ####
     ) q
     on q.item_id = i.item_id;

发布原始查询,一个简单的左连接会有所帮助。