Mysql查询用union和where

时间:2012-06-29 16:43:58

标签: mysql union where-clause

在以下查询中,我想添加一个where语句,将结果范围缩小到m.extracard>0的结果:

SELECT u.id, u.onoma_u, u.name_u,
coalesce(u.programa, a.programa) as programa,
coalesce(u.barcode, a.barcode) as barcode,
coalesce(u.plan, a.plan) as plan,
coalesce(u.im_exp, a.im_exp) as im_exp,
coalesce(u.symb, a.symb) as symb
FROM (SELECT a1.id, a1.onoma_u, a1.name_u, a1.programa, 
             a1.barcode, a1.plan, a1.im_exp, a1.symb
      FROM aitisi a1 
      where a1.id between 6017 and 6063
      UNION
           SELECT a2.id, m.name, m.surname, NULL, NULL, NULL, NULL, NULL
           FROM members m 
           JOIN aitisi a2 ON a2.id = m.symbid 
           WHERE m.extracard > 0
       ) u
JOIN aitisi a ON a.id = u.id 
where a.id between 6017 and 6063

但是在结果中我得到的ID超出了范围之间。 我有机会把WHERE m.extracard > 0放在错误的地方吗?

1 个答案:

答案 0 :(得分:0)

SELECT u.id, u.onoma_u, u.name_u,
coalesce(u.programa, a.programa) as programa,
coalesce(u.barcode, a.barcode) as barcode,
coalesce(u.plan, a.plan) as plan,
coalesce(u.im_exp, a.im_exp) as im_exp,
coalesce(u.symb, a.symb) as symb
FROM (SELECT a1.id, a1.onoma_u, a1.name_u, a1.programa, 
             a1.barcode, a1.plan, a1.im_exp, a1.symb
      FROM aitisi a1 
      JOIN mwmbers m ON a1.id = m.symbid 
           WHERE m.extracard > 0
      where a1.id between 6017 and 6063
      UNION
           SELECT a2.id, m.name, m.surname, NULL, NULL, NULL, NULL, NULL
           FROM members m 
           JOIN aitisi a2 ON a2.id = m.symbid 
           WHERE m.extracard > 0
       ) u
JOIN aitisi a ON a.id = u.id 
where a.id between 6017 and 6063