我有以下2张桌子
tableA a(ID,名称,姓氏,程序,日期)
tableB b(编号,帮助,姓名,姓氏,外卡)
与tableA.id = tableB.aid(1至n的关系)
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 |
在结果中,表B的每个成员应具有表A的所有值(程序,日期,到期日等),并在同一列中仅显示名称,表B的姓(同名)。另外,我需要对(%id1和%id2)之间的a.id使用ween子句,还需要WHERE语句来选择tableB.card = 1的行
| 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 |
最佳答案
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
编辑:
请参考http://sqlfiddle.com/#!2/d8227/1
关于mysql - MySQL UNION与WHERE,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/11409004/