2012-08-08 56 views
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 
    } 
} 

回答

1

UNION您需要爲每個聯合查詢具有相同的列號,列名稱。因此,在第一個查詢中,您有來自項目表的列,但在第二個查詢中,您有來自項目,項目地區和用戶表的列。

+0

THX爲你的答覆,但問題是一個MySQL錯誤「列'id_project'字段列表中是不明確的」。請參閱下面的答案。 – joko13 2012-08-08 10:27:52

+0

xto的答案是正確的答案。 joko13你的回答是xto的解釋的結果... – Nico 2014-02-07 14:56:43

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