尝试使用逻辑aritmethics从多个表中收集数据

时间:2015-11-02 15:43:47

标签: oracle logic

我正在尝试使用逻辑aritmethics从多个表中收集数据:OR AND NOT UNION INTERSECT。 我有3个表:客户,航班,预订。

Table1

Table 2-3

我的目标是从客户表中获得所有持有不止一次航班的护照。

为助手提供帮助。

2 个答案:

答案 0 :(得分:1)

使用group byhaving条款。限制那些计数> 1

的行

模式

create table bookings
(
    id int auto_increment primary key,
    passportno int not null,
    flightnumber int not null,
    `day` date not null,
    row varchar(10) not null,
    seat varchar(10) not null
);
insert bookings(passportno,flightnumber,`day`,row,seat) values (1,2,'2005-01-01',1,1); -- Joe
insert bookings(passportno,flightnumber,`day`,row,seat) values (1,3,'2005-02-01',1,1); -- Joe
insert bookings(passportno,flightnumber,`day`,row,seat) values (2,3,'2005-02-01',2,2); -- Sally


create table customers
(
    passportno int primary key,
    name varchar(100) not null,
    address varchar(100) not null,
    phone varchar(20) not null
);
insert customers(passportno,name,address,phone) values (1,'Joe','addr','ph');
insert customers(passportno,name,address,phone) values (2,'Sally','addr','ph');

查询和结果

select c.passportno
from customers c 
join bookings b 
on c.passportno=b.passportno 
group by c.passportno 
having count(b.id)>1;

+------------+
| passportno |
+------------+
|          1 |
+------------+

名为MySQL Handling of GROUP BY

的Mysql手册页

答案 1 :(得分:0)

如果我理解这个问题,那么查询应该是

SELECT c.PASSPORTNO
  FROM CUSTOMERS c
  WHERE c.PASSPORTNO IN (SELECT DISTINCT PASSPORTNO
                           FROM (SELECT PASSPORTNO, FLIGHTNUMBER, COUNT(*)
                                   FROM BOOKINGS
                                   GROUP BY PASSPORTNO, FLIGHTNUMBER
                                   HAVING COUNT(*) > 1)

祝你好运。