【问题标题】:Subquery select with outer value for inner where clause子查询选择内部 where 子句的外部值
【发布时间】:2020-07-29 19:05:08
【问题描述】:

用户可以在订阅表中拥有多条记录。

我想要做的是返回他们的名字、姓氏、电子邮件、开始日期(他们的第一次订阅,从订阅顺序中选择 start_date 按 start_date asc 限制 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

这会为每个人返回相同的 start_date,因为它可能会提取匹配的第一个。

SQL 修改架构:http://sqlfiddle.com/#!9/245c05/5

【问题讨论】:

标签: mysql sql subquery


【解决方案1】:

这个查询:

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  

请参阅demo
结果:

| 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 |

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-22
    • 2023-03-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-29
    • 2016-10-01
    相关资源
    最近更新 更多