I'm trying to build an SQL query but I'm receiving the following error:
#1054 - Unknown column 'r.id' in 'where clause'
This is my query:
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
I haven't used sub-queries before, so I assume this is where I'm failing. Your help is greatly appreciated!
MySQL doesn't accepted alias to parent in subquery. You should join instead:
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
i post it as answer. You have use wrong backticks
change this:
WHERE `r.id`=`rc.rate_id`
to
WHERE `r`.`id`=`rc`.`rate_id`
sample
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]>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.