我在尝试理解 View 、联合和连接的工作原理时遇到了麻烦,
我的看法是:
SELECT
id,
CODE,
NAME,
type,
quantity
FROM
items
UNION ALL
SELECT
id,
CODE,
NAME,
type,
price,
quantity
FROM
inventory_items
表项没有名为数量的列,但我仍然需要从 inventory_items 中获取该值,如果我从我获得的项中删除对数量的选择:
[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near FROM items
如果我离开选择我得到:
[Err] 1054 - Unknown column 'quantity' in field list'
我到底想完成什么?我想使用唯一列从这些表中选择所有数据,我不想像 name1、name2 列等。
这样做的正确方法是什么?
最佳答案
UNION 期望每组结果中的列数相同。如果您有一个始终为空的列,您可以简单地选择 NULL 而不是一个真正的列。请注意,列名取自第一个 SELECT,因此您需要为 NULL 添加别名(或者只是切换 SELECT)
SELECT
id,
CODE,
NAME,
type,
NULL AS price,
NULL AS quantity
FROM
items
UNION ALL
SELECT
id,
CODE,
NAME,
type,
price,
quantity
FROM
inventory_items
关于php - Mysql Unknown column on View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33977579/