假设我想使用 UNION 从 2 个不同的表(具有相同的结构)中获取记录。
查询是这样的:
SELECT * FROM (
(SELECT `a1`.`title`, `a1`.`updated_date`, `a1`.`plain_description`, `a1`.`thumb`, `a1`.`link`, `c1`.`alias` as category_alias
FROM (`articles1` as a1)
LEFT JOIN `article_categories1` as c1 ON `c1`.`id`=`a1`.`category_id`
WHERE `a1`.`visible` = 1 AND `c1`.`alias` = 'category-alias' AND `c1`.`visible` = 1)
UNION
(SELECT `a2`.`title`, `a2`.`updated_date`, `a2`.`plain_description`, `a2`.`thumb`, `a2`.`link`, `c2`.`alias` as category_alias
FROM (`articles2` as a2)
LEFT JOIN `article_categories2` as c2 ON `c2`.`id`=`a2`.`category_id`
WHERE `a2`.`visible` = 1 AND `c2`.`visible` = 1)
) as t ORDER BY t.updated_date DESC LIMIT 0, 5
当我执行查询时,它显示:
[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 'LEFT JOIN `article_categories2` as c2 ON `c2`.`id`=`a2`.`category_id`
这里出了什么问题?
**`UPDATED`**
删除子查询中的括号解决了这个问题。还有一件事,我怎么能在每条记录中添加一个字段来告诉我它属于哪个表。假设我想要这样的东西:
id | title | link | table
-----------------------------------------------------
1 | Title 1 | somelink.html | articles1
2 | Title 2 | link2 .html | articles2
3 | Title 3 | link3 .html | articles1