mysql连接表

时间:2012-01-04 04:23:22

标签: mysql sql join union

我是新手加入桌子。

ClassList
========================
ID      Level
1       2
2       2
3       4
4       1
5       3
6       7

BoysList
========================
ID      Name        Age
1       Alex        13
2       Arnold      16
3       Barny       15

GirlsList
========================
ID      Name        Age
4       Arnie       12
5       Martha      17
6       Beth        15

我能够加入两张桌子。但是,如果在这种情况下,你必须首先组合两个表(BoysList和GirlsList),然后将它与ClassList连接起来。

结果集将是:

Result
================================================
ID      Name
4       Arnie           
6       Beth        
5       Martha      
1       Alex    
2       Arnold  
3       Barny       

结果的顺序将是男孩女孩的名单,名字ASC。怎么做到这一点?

3 个答案:

答案 0 :(得分:5)

你要做的第一件事是UNION BoysList和GirlsList然后INNER JOIN它与ClassList

SELECT  iStudentList.`ID`,
    iStudentList.`Name`,
    iStudentList.`Age`,
    ClassList.`iOrder`
FROM
ClassList INNER JOIN 
    (SELECT `ID`, `Name`, `Age`, "A" as iOrder FROM BoyssList
        UNION
     SELECT `ID`, `Name`, `Age`, "B" as iOrder FROM GirlsList) as iStudentList
ON ClassList.`ID` = iStudentList.`ID`
ORDER BY ClassList.`iOrder` DESC, iStudentList.`Name` ASC

答案 1 :(得分:1)

您可以使用union all (希望这个查询不是错误的)

select cl.id, bl.name
from ClassList cl, BoysList bl
where cl.id = bl.id
order by bl.name
union all
select cl.id, gl.name
from ClassList cl, GirlsList gl
where cl.id = gl.id
order by cl.name

修改查询:

select cl.id, bl.name, 'A' as ket
from boyList bl, classList cl
where bl.id = cl.id
union all
select cl.id, gl.name, 'B' as ket
from girlList gl, classList cl
where gl.id = cl.id
order by ket desc, name

答案 2 :(得分:1)

UNION外,您还可以使用OUTER JOIN

SELECT 
    cl.ID                         AS ID
  , COALESCE(b.`Name`, g.`Name`)  AS Name
  , COALESCE(b.Age, g.Age)        AS Age
  , cl.`Level`                    AS Level
FROM
      ClassList AS cl
  LEFT OUTER JOIN 
      BoysList AS b
          ON b.ID = cl.ID
  LEFT OUTER JOIN 
      GirlsList AS g
          ON g.ID = cl.ID