gpt4 book ai didi

MySQL 与 WHERE 的 UNION

转载 作者:行者123 更新时间:2023-11-29 14:23:24 24 4
gpt4 key购买 nike

我有以下2个表tableA a (id, 姓名, 项目, 日期)tableB b(id、aid、姓名、extracard)with 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 |

在结果中,tableB 的每个成员都应具有 tableA 中的所有值(计划、日期、过期时间等...),并且仅在同一列中显示 tableB 中的姓名、姓氏(合并??)。另外,我需要在 (%id1 和 %id2) 之间使用 a.id 的 Between 子句,还需要使用 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 与 WHERE 的 UNION,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11409004/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com