我有三个表:categories和deals1和deals2。
我有下一个mySQL句子,它有效:
SELECT name,
(SELECT categoria FROM categorias WHERE categorias.id = deals.id) AS categoria
from deals1 where id = '1'
但是现在,我需要使用UNION ALL从两个不同的表中获取数据......这样的事情:
(SELECT name,
(SELECT categoria FROM categorias WHERE categorias.id = deals1.id) AS categoria
from deals1 where id = '1')
UNION ALL
(SELECT name,
(SELECT categoria FROM categorias WHERE categorias.id = deals2.id) AS categoria
from deals2 where id = '1')
它返回错误....¿获取联合数据的正确方法是什么?
非常感谢!
EDITED: 我发现了问题...
在我的项目中,我有:
... SELECT categoria FROM categorias WHERE categorias.id = **deals2.id**) AS categoria
from **deals1** where id = '1')
接下来是正确的句子......如果你付出了注意力,你会看到差异(强词)......
(SELECT name,
(SELECT categoria FROM categorias WHERE categorias.id = **deals2.id**) AS categoria
from **deals2** where id = '1')
感谢所有人!
答案 0 :(得分:1)
语法看起来正确,唯一困扰我的是括号:
我的查询的语法始终是:
SELECT name,
(SELECT categoria FROM categorias WHERE categorias.id = deals1.id) AS categoria
from deals1 where id = '1'
UNION ALL
SELECT name,
(SELECT categoria FROM categorias WHERE categorias.id = deals2.id) AS categoria
from deals2 where id = '1';
没有外部括号...
请注意 - subselect中的表格应为deals1 / deals2 - not deals。
但是 - 你得到的错误是什么?
另外 - 你想使用union all或union(你想要同样的结果出现一次,还是多次)?工会还会添加隐含的" distinct"通过措辞 - 我认为你期望,但我不确定(联盟所有只会连接结果,如果产生相同的记录结果会重复)
答案 1 :(得分:0)
首先检查表名,你说的是deals1和deals2,但是在union all中第一个查询
(SELECT name,
(SELECT categoria FROM categorias WHERE categorias.id = deals.id) AS categoria
from deals where id = '1')
其"交易"。