在我的数据库中,潜在顾客可以有很多任务,因此任务表有一个taskable_id和taskable_type,其中taskable_id是lead的id,taskable_type是Lead,遵循Ruby on Rails多态约定。在Mysql中使用LIMIT子查询
我想为约会状态为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 |
你第二个选项无'on'关键字,所以你的连接无效。你基本上将内连接(foo)作为t1(bar)作为t2' – 2014-09-25 18:03:09
你可以显示一些示例数据吗? – Mihai 2014-09-25 18:03:31
@MarcB但是我没有看到在这里会有用的地方。 t1和t2之间没有关系。我只是想为所有潜在客户找到第一个任务。 – Donato 2014-09-25 18:05:17