带有WHERE的MySQL UNION

时间:2012-07-10 08:01:57

标签: mysql union

我有以下2个表格 tableA a(id,name,surname,program,date) tableB b(id,aid,name,surname,extraracard) with tableA.id = tableB.aid(1 to n relationship)

Sample data for tableA:
| ID | NAME  | SURNAME | PROGRAM |   DATE    |  EXPIRES  |
----------------------------------------------------------
| 1  | TOM   | JONES   | 1,2,3   | 12/8/2012 | 12/8/2013 |
| 2  | JAMIE | OLIVER  | 4,5,6   | 15/8/2012 | 15/8/2013 |

Sample data for tableB:
| ID | AID | NAME  | SURNAME | CARD |
-------------------------------------
| 1  |  1  | ANNE  | JONES   |  1   |
| 2  |  1  | JACK  | BOWER   |  0   |
| 3  |  2  | KATE  | PERRY   |  1   |
| 4  |  2  | JOHN  | DOE     |  0   |
| 5  |  2  | HARRY | POTTER  |  0   |

在结果中,tableB的每个成员都应该拥有tableA中的所有值(程序,日期,过期等),并且只显示同一列中tableB 的名称,姓氏(合并??)。另外,我需要在(%id1和%id2)之间使用a.id的between子句以及用于选择tableB.card = 1

的行的WHERE语句
| a.ID | NAME  | SURNAME | PROGRAM |   DATE    |  EXPIRES  |
------------------------------------------------------------
|  1   | TOM   | JONES   | 1,2,3   | 12/8/2012 | 12/8/2013 |
|  1   | ANNE  | JONES   | 1,2,3   | 12/8/2012 | 12/8/2013 |
|  2   | JAMIE | OLIVER  | 4,5,6   | 15/8/2012 | 15/8/2013 |
|  2   | KATE  | PERRY   | 4,5,6   | 15/8/2012 | 15/8/2013 |

3 个答案:

答案 0 :(得分:1)

 SELECT * FROM 
   ( (SELECT a.id ,a.name,a.surname,a.program,a.date,a.expires 
    from tableA a left outer join tableB b 
    on b.aid=a.id 
    where b.card=1 and (a.id between '1' and '2'))
    UNION ALL
    (SELECT a.id ,b.name,b.surname,a.program,a.date,a.expires 
    from tableA a left outer join tableB b 
    on b.aid=a.id 
    where b.card=1 and (a.id between '1' and '2'))) t
    ORDER BY id

EDITED: 请参阅http://sqlfiddle.com/#!2/d8227/1

答案 1 :(得分:0)

你在寻找 -

(SELECT a.id, name, surname, program, date, expires FROM tableA a WHERE a.id BETWEEN '%id1' and '%id2')
UNION
(SELECT a.id, b.name, b.surname, program, date, expires FROM tableB b LEFT JOIN tableA a ON b.aid=a.id WHERE b.card=1 AND (a.id between '%id1' and '%id2') )
ORDER BY a.id ASC

答案 2 :(得分:0)

(select a.ID,a.NAME,a.SURNAME,a.PROGRAM,a.DATE,a.EXPIRES from tableA a where ...)    
Union All    
(select a2.ID,b.NAME,b.SURNAME,a2.PROGRAM,a2.DATE,a2.EXPIRES from tableB b 
 left join tableA a2 on b.aid = a2.id where ...);

您可以根据自己的需要和left/inner join条件选择where between条款,例如.. where id between 2 and 8where id > 2 and id < 8