Mysql查询组合

时间:2013-06-25 07:17:36

标签: php mysql

我有一个由3个表a,b,c组合而成的查询,这里的问题是表c存在于2个数据库D1和D2中,所以我必须从两个数据库中获取表c的记录。表a和b仅来自数据库D1,

查询是:

$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,如果我从查询中避开字段'school'它工作正常,但我也必须获取字段'school',我该如何修改查询。感谢:)

3 个答案:

答案 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";

答案 1 :(得分: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";

答案 2 :(得分: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
";