开发者

Scalable single query that pulls rows with multple unique primary ids

So I've got ratings for items by users in a mysql database, and I was wondering whats the best way to check if a list of items has rated by a user.

  1. I could pull all the items a user has ever rated in a single query and then go through that set looking for items in my list.
  2. The other way would be to use a single query to check for each item to see if its been rated.

The first way has the benefit of using a single query, the second one doesn't require me to pull all items a user has ever rated. Which one is better? I'm new to sql so I'm not really sure how bad query overhead is. Additionally, if you have better suggestions, feel free to give them.

As requested, here is an example table.

CREATE TABLE ratings (
  user id I开发者_运维百科NT NOT NULL, 
  item_id INT NOT NULL, 
  rating INT NOT NULL
);


If you were using a single query for each item, you would be scanning/seeking ratings so many times how many items you've got. Maybe I'm missing something, but so far I can't see how it's better than using one query to check all the items.

Besides, operating on sets is actually what SQL is best fit for, isn't it?

So here's an example query for checking all the list of items.

SELECT
  il.item_id,
  CASE
    WHEN r.item_id IS NULL THEN 'No'
    ELSE 'Yes'
  END AS IsRated
FROM itemlist il
  LEFT JOIN ratings r ON il.item_id = r.item_id
                     AND rating > 0
                     AND user = @user

It is assumed that one user can only rate one item once, so I'm not trying to suppress duplicates here.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜