subquery为内部where子句选择外部值

2w3rbyxf  于 2021-07-27  发布在  Java
关注(0)|答案(1)|浏览(281)

用户在subscriptions表中可以有多条记录。
我要做的是返回他们的名字、姓氏、电子邮件、开始日期(对于他们的第一个订阅,请从订阅中选择“开始日期”order by start\u date asc limit 1,但我需要为该特定用户提供)

// users
id
first_name
last_name
email

// subscriptions
id
email
start_date (TIMESTAMP)
end_date (TIMESTAMP)
status

我原以为这样行得通,但似乎不行:

select 
    distinct(users.email), status, first_name, last_name,
    (select start_date from subscriptions where subscriptions.email = users.email order by start_date asc limit 1) as start_date 
from 
    subscriptions sub 
join 
    users u on sub.email = u.email
order by 
    sub.end_date desc

这会为每个人返回相同的开始日期,因为它可能会拉第一个匹配的开始日期。
sql摆弄模式:http://sqlfiddle.com/#!9/245c05/5号机组

xdnvmnnf

xdnvmnnf1#

此查询:

select s.*
from subscriptions s
where s.start_date = (select min(start_date) from subscriptions where email = s.email)

返回每个用户的第一个订阅的行。
加入到 users :

select u.*, t.status, t.start_date
from users u 
left join (
  select s.*
  from subscriptions s
  where s.start_date = (select min(start_date) from subscriptions where email = s.email)  
) t on t.email = u.email

请看演示。
结果:

| id  | email          | first_name | last_name | status   | start_date          |
| --- | -------------- | ---------- | --------- | -------- | ------------------- |
| 1   | john@aol.com   | John       | Smith     | active   | 2018-02-12 23:34:02 |
| 2   | jim@aol.com    | Jim        | Smith     | canceled | 2016-03-02 23:34:02 |
| 3   | jerry@aol.com  | Jerry      | Smith     | active   | 2017-12-12 23:34:02 |
| 4   | jackie@aol.com | Jackie     | Smith     | active   | 2018-05-22 23:34:02 |

相关问题