$ wpdb-> get_results在查询中使用UNION

时间:2012-08-08 09:32:32

标签: sql wordpress union

当自己运行以下每个SELECT(没有UNION)时,我得到了预期的结果。使用UNION时我没有得到任何结果。

为什么这不起作用的任何想法?

$query = "
 (SELECT * FROM projects WHERE public='1')
 UNION
 (SELECT * FROM projects JOIN project_region ON projects.id_project = project_region.id_project 
 JOIN user ON user.id_region = project_region.id_region WHERE user.user_id = {$current_user->ID})
 UNION
 (SELECT * FROM projects JOIN project_user ON projects.id_project = project_user.id_project
 WHERE project_user.user_id = {$current_user->ID})
";

$projects = $wpdb->get_results($query);

if ($projects) {
   foreach ($projects as $project) {
      // output results
   }
}

2 个答案:

答案 0 :(得分:1)

UNION中,您需要为每个联合查询提供相同的列号,列名。因此,在第一个查询中,您有来自项目表的列,但在第二个查询中,您有来自项目,project_region和用户表的列。

答案 1 :(得分:0)

MYSQL错误是*字段列表中的列'id_project'不明确*

所以工作查询如下所示:

$query = "
(SELECT id_project, name FROM projects WHERE public='1')
UNION
(SELECT projects.id_project, projects.name FROM projects JOIN project_region ON projects.id_project = project_region.id_project 
JOIN user ON user.id_region = project_region.id_region WHERE user.user_id = {$current_user->ID})
UNION
(SELECT projects.id_project, projects.name FROM projects JOIN project_user ON projects.id_project = project_user.id_project
WHERE project_user.user_id = {$current_user->ID})
";

我在这里找到了解决方案: http://sqlzoo.net/howto/source/z.dir/err918/mysql