如何在一个查询中创建复杂查询,如使用MS Access?

时间:2014-07-23 07:06:23

标签: sql ms-access

我正在使用MS Access来汇总内容 举个例子,假设我有以下3个查询

1。取得所有年龄超过20岁的男性

1. select users.id, users.name, users.age, users.gender 
   from users
   where users.age > 20 AND users.gender = 1   (means male)

2。获取所有制作“福特”的汽车

2. select cars.user_id, cars.make, cars.name_of_car
   from cars
   where cars.make = "FORD"

第3。记录2014年最近发生的所有事故

3. select accidents.user_id, accidents.car_accident_date_ymd
   from accidents
   group by accidents.user_id
   having (((max(accidents.car_accident_date_ymd)) Like "2014*"));

在第4次查询时,我将它们连接在一起

users.id(1) = (n)cars.user_id
users.id(1) = (1)accidents.user_id

然后显示

`users.id, users.name, users.age, users.gender, cars.make, accidents.car_accident_date_ymd`

如何在一个查询中将它们全部放在一起? 如果可能的话,我想使用上面的所有3个查询并以某种方式将它们组合在一起 有什么想法吗?

2 个答案:

答案 0 :(得分:1)

您需要JOIN

SELECT users.id, 
       users.name, 
       users.age, 
       users.gender, 
       cars.make, 
       accidents.car_accident_date_ymd 
FROM   users users 
       JOIN cars cars 
         ON users.id = cars.user_id 
       JOIN accidents accidents 
         ON accidents.user_id = users.id 
WHERE  users.age > 20 
       AND users.gender = 1 
       AND cars.make = "ford" 
GROUP  BY accidents.user_id 
HAVING (( ( Max(accidents.car_accident_date_ymd) ) LIKE "2014*" )); 

答案 1 :(得分:1)

select users.id, users.name, users.age, 
users.gender, cars.make, max(accidents.car_accident_date_ymd)
from accidents 
join users on users.id = accidents.user_id
join cars on cars.user_id = users.id
where users.age > 20 
    and users.gender = 1 
    and cars.make = 'FORD'
group by users.id, users.name, users.age, 
users.gender, cars.make
having max(accidents.car_accident_date_ymd) Like "2014*"

上述查询假设您要选择最新的car_accident_date_ymd,如果您想要选择您需要将其包含在group by中的每个唯一身份,这意味着您可能会重复结果集中的用户即

select users.id, users.name, users.age, 
users.gender, cars.make, accidents.car_accident_date_ymd
from accidents 
join users on users.id = accidents.user_id
join cars on cars.user_id = users.id
where users.age > 20 
    and users.gender = 1 
    and cars.make = 'FORD'
group by users.id, users.name, users.age, 
users.gender, cars.make, accidents.car_accident_date_ymd
having max(accidents.car_accident_date_ymd) Like "2014*"