我试图从两个不同的表中获取数据,使用不同的字段名称,如
表1
user_id user_grp_id
1 1
2 1
表2
cust_id cust_grp_id
1 2
2 2
现在我使用像这样的查询
Select * from table 1 Union All select * from table 2
显示结果如此
Array
(
[0] => Array
(
[user_id] => 1
[user_grp_id] => 1
)
[1] => Array
(
[user_id] => 2
[user_grp_id] => 1
)
[2] => Array
(
[user_id] => 1
[user_grp_id] => 2
)
[3] => Array
(
[user_id] => 2
[user_grp_id] => 2
)
现在我们可以看到第二个表的结果也在第一个表的字段名下,但我希望得到这样的结果。
Array
(
[0] => Array
(
[user_id] => 1
[user_grp_id] => 1
)
[1] => Array
(
[user_id] => 2
[user_grp_id] => 1
)
[2] => Array
(
[cust_id] => 1
[cust_grp_id] => 2
)
[3] => Array
(
[cust_id] => 2
[cust_grp_id] => 2
)
如何实现这种结果。
修改
答案中给出的查询结果是
Array
(
[0] => Array
(
[user_id] => 1
[user_grp_id] => 1
[cust_id] => NULL
[cust_grp_id] => NULL
)
[1] => Array
(
[user_id] => 2
[user_grp_id] => 1
[cust_id] => NULL
[cust_grp_id] => NULL
)
[2] => Array
(
[user_id] => NULL
[user_grp_id] => NULL
[cust_id] => 1
[cust_grp_id] => 2
)
[3] => Array
(
[user_id] => NULL
[user_grp_id] => NULL
[cust_id] => 2
[cust_grp_id] => 2
)
答案 0 :(得分:5)
如果您有不同的字段具有不同的名称,则不应将它们返回到相同的位置。您可以使用空值来填充空槽。 所以你可以这样做:
SELECT user_id, user_grp_id, NULL AS cust_id, NULL AS cust_grp_id FROM table1
UNION ALL
SELECT NULL AS user_id, NULL AS user_grp_id, cust_id, cust_grp_id FROM table2
sqlfiddle here