0

我有以下 2 个表 tableA a (id, name, surname, program, date) tableB b (id,aid, name, surname, extracard) with tableA.id = tableB.aid (1 to 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 的名称、姓氏(coalesce??)。此外,我需要在 (%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 |
4

3 回答 3

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

已编辑:请参阅http://sqlfiddle.com/#!2/d8227/1

于 2012-07-10T08:06:48.563 回答
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
于 2012-07-10T08:15:37.373 回答
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

于 2012-07-10T08:18:42.843 回答