内部 where 子句具有外部值的子查询 select
Subquery select with outer value for inner where clause
用户可以在订阅中有多个记录table。
我想做的是 return 他们的名字、姓氏、电子邮件、开始日期(他们的第一个订阅,select 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
return对每个人来说都是一样的start_date,因为它可能会拉出它匹配的第一个。
SQL fiddle 架构:http://sqlfiddle.com/#!9/245c05/5
这个查询:
select s.*
from subscriptions s
where s.start_date = (select min(start_date) from subscriptions where email = s.email)
returns 每个用户的第一个订阅行。
加入 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 |
用户可以在订阅中有多个记录table。
我想做的是 return 他们的名字、姓氏、电子邮件、开始日期(他们的第一个订阅,select 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
return对每个人来说都是一样的start_date,因为它可能会拉出它匹配的第一个。
SQL fiddle 架构:http://sqlfiddle.com/#!9/245c05/5
这个查询:
select s.*
from subscriptions s
where s.start_date = (select min(start_date) from subscriptions where email = s.email)
returns 每个用户的第一个订阅行。
加入 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 |