我只是想说这个论坛在我目前的工作中确实对我有很大帮助。

在为我们的ms访问数据库编写sql查询时,我需要其他帮助。想法是对所有表(1月至12月)进行联合查询,以获取唯一的ID号,并每月将其“项目”值作为输出表中的列。

可以在下面看到一个例子。如果在表中找不到ID,则该值将返回null。

这在excel中似乎很容易做到,但我们希望在后端进行。我只为所有表写下了UNION查询,但这就是我得到的结果。

先谢谢您的帮助。

表1:一月

 |    ID    |   Item    |
 |    1     |   Apple   |
 |    2     |   Salad   |
 |    3     |   Grapes  |


表2:2月

 |    ID    |   Item    |
 |    1     |   Apple   |
 |    2     |   Grapes  |
 |    4     |   Grapes  |


输出表:

 |    ID    |   January   |   February   |
 |    1     |    Apple    |   Apple      |
 |    2     |    Salad    |   Grapes     |
 |    3     |    Grapes   |   NULL       |
 |    4     |    NULL     |   Grapes     |

最佳答案

一种方法是使用union allgroup by

select id, max(January) as January, max(February) as February
from (select id, item as January, NULL as February from January
      union all
      select id, NULL, item from February
     ) jf
group by id;

关于mysql - 对具有新列的多个表进行UNION查询,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/26921547/

10-13 07:56
查看更多