tags:

views:

187

answers:

2

I have a table with a field called 'user_car'. It consists of a cat'd underscore separated value (user's id _ car's id)

user_car          rating
-----------------------------
11_56748           4
13_23939           2
1_56748            1
2001_56748         5
163_23939          1

I need to get the average rating for any "car". In my example table, there are only 2 cars listed: 56748 and 23939. So say I want to get the average rating for the car: 56748, so far I have this SQL, but I need the correct regex. If I'm totally off-base, let me know. Thanks!

$sql = "
 SELECT AVG 'rating' FROM 'car_ratings'
 WHERE 'user_car' REGEXP ''; 
";
+3  A: 

I don't see why you need to use REGEXes ...

SELECT AVG(`rating`) FROM `car_ratings` WHERE `user_car` LIKE '%_56748'

Regexes are slow and can pretty easily shoot you in the foot. I learned to avoid them in MySQL whenever I could.

Martin Hohenberg
+1 for `LIKE`. Keep in mind that you may get down-voted into oblivion for saying negative things about regexes (true though they may be) :-) Also, shouldn't `AVG` argument be enclosed in parenthesis?
ChssPly76
AVG in parenthesis: This happens when you copy stuff from questions :)
Martin Hohenberg
Actually LIKE probably won't be noticeably quicker than RLIKE/REGEXP in this case, as it can't left-optimise it. However, it's definitely still a plus because LIKE is ANSI SQL compliant; regexes are MySQL-specific. Also, regexes are a pile of poo. ;-)
bobince
@ChessPly: regex expressions in the database are silly slow given the performance parameters placed upon databases. Saying "don't use regex in a database" is valid. Saying "don't use regex because I can't use them" isn't.
Stefan Kendall
+4  A: 

You can extract the car id using:

substring(user_car from (locate('_', user_car) + 1))

this will allow you to do:

select   substring(user_car from (locate('_', user_car) + 1)) as car_id,
         avg(rating)
from     car_ratings
group by car_id

But, this is a bad idea. You would be much better off splitting user_car into user_id and car_id.

James McNellis
How do you know (s)he uses PHP to access the database?
Martin Hohenberg
I don't; did I say something about PHP?
James McNellis
need more sleep, my fault, sorry -_-
Martin Hohenberg
The interim solution would be to implement your query as a view, which has been supported in MySQL since 5.0.1. That is a fugly data model, no doubt...
OMG Ponies