tags:

views:

37

answers:

1

I am probably trying to accomplish too much in a single query, but have I an sqlite database with badly formatted recipes. This returns a sorted list of recipes with relevance added:

SELECT *, sum(relevance) FROM (
  SELECT *,1 AS relevance FROM recipes WHERE ingredients LIKE '%milk%' UNION ALL
  SELECT *,1 AS relevance FROM recipes WHERE ingredients LIKE '%flour%' UNION ALL
  SELECT *,1 AS relevance FROM recipes WHERE ingredients LIKE '%sugar%'
) results GROUP BY recipeID ORDER BY sum(relevance) DESC;

But I'm now stuck with a special case where I need to write the relevance value to a field on the same row as the recipe. I figured something along these lines:

UPDATE recipes SET relevance=(SELECT sum(relevance) ...)

But I have not been able to get this working yet. I will keep trying, but meanwhile please let me know how you would approach this?

Edit: Evaluating Peter's solution, I ran into some serious performance issues, due to the amount of data the operations had to be performed on. I wrote a little Rebol script that does the loops and and the finding and does commits in 1000-row batches. It completed in a couple of minutes.

+1  A: 

You really should get your model fixed (see below).

If you can't, the following query should work (I tried it and it worked as I expected).

Update recipes
Set relevance =
(
  Select   Case When ingredients Like '%milk%' Then 1 Else 0 End
         + Case When ingredients Like '%flour%' Then 1 Else 0 End
         + ...
  From recipes r2
  Where r2.recipe_id = recipes.recipe_id
)

It uses Case to sum up all matched ingredients.


Suggested model:

  • Table recipes

  • Table ingredients

  • Table recipe_ingredients

    • recipe_id
    • ingredient_id
Peter Lang
I agree, but it's much too broken to begin with. It seems basically a html scrape and I don't have the regexp-fu to divide the ingredients properly. Luckily, if I can get the relevance thing sorted, I won't have to touch it any more.. :)
luminarious
@luminarious: Well, then make sure to try the query I provided :)
Peter Lang
Does the syntax imply automatic summing, or you just missed the `SUM` invokation?
newtover
@newtover: That's what adding (`+`) the separate `Case` clauses is for. Every ingredient that is matched results in `1`, and I'm summing all those up. I do not group any rows here, so `SUM` would not work.
Peter Lang
@Peter Lang: I am sorry, I missed that all ingridients for the recipe are stored in a single row.
newtover