2013-06-25 335 views
0

我有一個由3個表a,b,c組合而成的查詢,這裏的問題是表c存在於2個數據庫D1和D2中,所以我必須從兩個數據庫中爲表獲取記錄ç。表a和b是從單獨的數據庫D1,Mysql查詢組合

查詢是:

$strQuery="SELECT a.id, b.lastname, school " ."FROM D1.a,D1.b" . 
    " WHERE a.idint = (select c_idint from D1.c where Cid IN(10) 
UNION select c_idint from D2.c where Cid IN(10) order by c_idint) 
AND a.idint = b.idb"; 

的問題是場「學校」是表C,如果我避免查詢外地「學校」它工作正常,但我也必須獲取「學校」字段,我如何修改查詢。謝謝:)

+0

使用'AS'到你的別名'D1.c'表到別的 – naththedeveloper

+0

*這是*的問題?怎麼樣在這個查詢中發生的所有其他垃圾 - 如果子查詢返回一個數組,以及停止和開始(「。」)是什麼? – Strawberry

+0

@Strawberry,在你喊之前請想想 –

回答

0

試試這個:

$strQuery="SELECT a.id, b.lastname, c.school as dSchool, '' as ddSchool " ."FROM D1.a,D1.b, D1.c" . 
    " WHERE a.idint = c.idint AND c.Cid IN (10) 
AND a.idint = b.idb 

UNION 

SELECT a.id, b.lastname, '' as dSchool, c.school as ddSchool " ."FROM D1.a,D1.b, D2.c" . 
    " WHERE a.idint = c.idint AND c.Cid IN (10) 
AND a.idint = b.idb 
"; 
+0

完美...完美.. –

2

你需要的是alias

$strQuery="SELECT a.id, b.lastname, D2.c.school as school1,D1.c.school as school2 " ."FROM D1.a,D1.b,D1.c,d2.c" . 
      " WHERE a.idint = (select c_idint from D1.c where Cid IN(10) 
      UNION select c_idint from D2.c where Cid IN(10) order by c_idint) 
      AND a.idint = b.idb"; 
+0

應該有一個'從表c'部分也在查詢右邊,但它從2個數據庫 –

+0

其給出錯誤 –

+0

什麼錯誤?我指導你,你想在我的查詢中更改數據庫或表名。 – Rikesh

0

給一個嘗試這樣的: -

$strQuery="SELECT a.id, b.lastname, c.school " ."FROM D1.a,D1.b,D1.c" . 
" WHERE a.idint = (select c_idint from D1.c where Cid IN(10) 
UNION select c_idint,school from D2.c where Cid IN(10) order by c_idint) 
AND a.idint = b.idb"; 
+0

,但是表c是從2個數據庫D1和D2獲取的 –

+0

@YipManWingChun在查詢學校中從數據庫D1和D2中獲取 –

+0

否,您將查詢作爲「」從D1獲取。 a,D1.b,D1.c「」沒有D2.c? –