在我的数据库中,一个主管可以有很多任务,因此任务表有一个taskable_id和taskable_type,其中taskable_id是引导的id,taskable_type是“Lead”,遵循Ruby on Rails多态约定。
我想为所有预约状态为1的潜在客户选择第一项任务。就是这样。结果集应该是一组任务。这就是我想出的:
SELECT
`tasks`.*
FROM
`tasks`
WHERE `tasks`.`taskable_id` IN (1, 2)
AND
`tasks`.`taskable_type` = 'Lead'
AND
`tasks`.`id`
IN
(
SELECT `tasks`.`id`
FROM `tasks`
WHERE `tasks`.`taskable_id` IN (1, 2)
AND
`tasks`.`taskable_type` = 'Lead'
AND
'appointment_status' = 1
ORDER BY created_at asc
LIMIT 1
);
但是这给出了错误“这个版本的MySQL还不支持'LIMIT& IN / ALL / ANY / SOME子查询”。其他stackoverflow帖子说,对于这个错误,LIMIT必须在子查询之外。
以下是示例数据:
mysql> SELECT * FROM tasks;
+----+------+--------+-------------+----------+---------------------+---------------------+-----------+---------------------+---------------------+---------------+-------------+
| id | name | status | description | priority | created_at | updated_at | task_type | date_start | date_due | taskable_type | taskable_id |
+----+------+--------+-------------+----------+---------------------+---------------------+-----------+---------------------+---------------------+---------------+-------------+
| 1 | NULL | 2 | NULL | 1 | 2014-09-24 17:53:58 | 2014-09-24 17:53:58 | 1 | 2014-09-25 11:30:00 | 2014-09-25 12:00:00 | Lead | 1 |
| 2 | NULL | 2 | NULL | 1 | 2014-09-25 12:45:50 | 2014-09-25 12:45:50 | 1 | 2014-09-25 12:45:00 | 2014-09-25 13:15:00 | Lead | 2 |
mysql> SELECT id, appointment_status, created_at, updated_at FROM leads;
+----+--------------------+---------------------+---------------------+
| id | appointment_status | created_at | updated_at |
+----+--------------------+---------------------+---------------------+
| 1 | 1 | 2014-09-24 17:45:12 | 2014-09-24 17:53:58 |
| 2 | 1 | 2014-09-25 12:45:46 | 2014-09-25 12:45:50 |
答案 0 :(得分:0)
经过一些实验,我觉得它有效:
SELECT
tasks.*
FROM
tasks
INNER JOIN
leads
ON leads.id = tasks.taskable_id AND tasks.taskable_type = "Lead"
WHERE
tasks.taskable_id IN (1, 2)
AND
(
tasks.id =
(
SELECT tasks.id
FROM tasks
WHERE tasks.taskable_id = leads.id
AND
tasks.taskable_type = "Lead"
AND
appointment_status = 1
ORDER BY created_at asc
LIMIT 1
)
)
答案 1 :(得分:0)
没有uservars的方法:
SELECT
tasks.*
FROM
(SELECT taskable_id,
MIN(t.created_at) created_at
FROM
tasks t
JOIN
leads l USING (taskable_id)
WHERE
taskable_id IN (1,2)
AND t.taskable_type = 'Lead'
AND l.appointment_status = 1
GROUP BY taskable_id
) x
JOIN
tasks
USING (taskable_id, created_at)