我正在尝试构建SQL查询但我收到以下错误:
#1054 - Unknown column 'r.id' in 'where clause'
这是我的疑问:
SELECT *, COUNT(id) AS result_count
FROM rate_clicks AS rc
WHERE click_type = 'details'
AND created_at > 1463517035
AND rate <= (SELECT rate
FROM rates AS r
WHERE r.id = rc.rate_id)
GROUP BY rate_id
ORDER BY result_count DESC LIMIT 5
我之前没有使用过子查询,所以我认为这是我失败的地方。非常感谢您的帮助!
答案 0 :(得分:1)
MySQL在子查询中不接受父级的别名。你应该加入:
SELECT *, COUNT(id) AS `result_count`
FROM `rate_clicks` AS `rc`
WHERE `click_type` = 'details' AND `created_at` > 1463517035
AND `rate` <= (SELECT `rate` FROM `rates` AS `r`
inner join `rate_clicks` as rc1 `r.id`=`rc1.rate_id`)
GROUP BY `rate_id`
ORDER BY `result_count` DESC LIMIT 5
答案 1 :(得分:1)
我发布它作为答案。你使用了错误的反引号
改变这个:
WHERE `r.id`=`rc.rate_id`
到
WHERE `r`.`id`=`rc`.`rate_id`
<强>样品强>
MariaDB [bb]> SELECT * FROM useindex i WHERE `i.num1`= 999 LIMIT 10;
ERROR 1054 (42S22): Unknown column 'i.num1' in 'where clause'
MariaDB [bb]>
MariaDB [bb]> SELECT * FROM useindex i WHERE `i`.`num1`= 999 LIMIT 10;
+-------+------+------+
| id | num1 | num2 |
+-------+------+------+
| 511 | 999 | 686 |
| 1878 | 999 | 687 |
| 3241 | 999 | 686 |
| 3245 | 999 | 688 |
| 4608 | 999 | 687 |
| 5971 | 999 | 685 |
| 5975 | 999 | 687 |
| 7338 | 999 | 686 |
| 8705 | 999 | 687 |
| 10068 | 999 | 686 |
+-------+------+------+
10 rows in set (0.00 sec)
MariaDB [bb]>