Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Count line breaks in a field and order by

Tags:

php

mysql

I have a field in a table recipes that has been inserted using mysql_real_escape_string, I want to count the number of line breaks in that field and order the records using this number.

p.s. the field is called Ingredients.

Thanks everyone

like image 523
bluedaniel Avatar asked Dec 13 '22 03:12

bluedaniel


1 Answers

This would do it:

SELECT *, LENGTH(Ingredients) - LENGTH(REPLACE(Ingredients, '\n', '')) as Count
FROM Recipes
ORDER BY Count DESC

The way I am getting the amount of linebreaks is a bit of a hack, however, and I don't think there's a better way. I would recommend keeping a column that has the amount of linebreaks if performance is a huge issue. For medium-sized data sets, though, I think the above should be fine.

If you wanted to have a cache column as described above, you would do:

UPDATE
    Recipes
SET
    IngredientAmount = LENGTH(Ingredients) - LENGTH(REPLACE(Ingredients, '\n', ''))

After that, whenever you are updating/inserting a new row, you could calculate the amounts (probably with PHP) and fill in this column before-hand. Or, if you're into that sort of thing, try out triggers.

like image 132
Paolo Bergantino Avatar answered Dec 24 '22 00:12

Paolo Bergantino