1

当自己运行以下每个 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
   }
}
4

2 回答 2

1

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

于 2012-08-08T10:05:54.900 回答
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

于 2012-08-08T10:19:01.147 回答