0

Let's assume I have the following tables:

items table
item_id|view_count

item_views table
view_id|item_id|ip_address|last_view

What I would like to do is: If last view of item with given item_id by given ip_address was 1+ hour ago I would like to increment view_count of item in items table. And as a result get the view count of item. How I will do it normally:

q = SELECT count(*) FROM item_views WHERE item_id='item_id' AND ip_address='some_ip' AND last_view < current_time-60*60

if(q==1) then q = UPDATE items SET view_count = view_count+1 WHERE item_id='item_id'

//and finally get view_count of item
q = SELECT view_count FROM items WHERE item_id='item_id'

Here I used 3 SQL queries. How can I merge it into one SQL query? And how can it affect the processing time? Will it be faster or slower than previous method?

4

2 回答 2

0
update target
    set target.view_count = target.view_count + 1
from items target
inner join (
    select item_id
    from item_views
    where item_id = 'item_id'
        and ip_address = 'some_ip'
        and last_view < current_time - 60*60
    ) ref
    on ref.item_id = target.item_id;

如上例所示,您只能使用连接将更新语句与条件结合起来;但您仍然需要单独的选择语句。在非常大的集合和/或未索引的表上可能会更慢。

于 2013-05-23T00:46:47.110 回答
0

我认为您的逻辑对于您所描述的内容不正确。查询:

SELECT count(*)
FROM item_views
WHERE item_id='item_id' AND
      ip_address='some_ip' AND
      last_view < current_time-60*60

正在计算比您的时间范围更早的观看次数。我想你想要:

      last_view > current_time-60*60

然后if q = 0在下一行。

MySQL 的性能相当不错not exists,所以以下应该可以正常工作: update items set view_count = view_count+1 WHERE item_id='item_id' and not exists (select 1 from item_views where item_id='item_id' AND ip_address='some_ip'和 last_view > current_time-60*60 )

item_views(item_id, ip_address, last_view)使用索引 on和索引 on会更好item(item_id)

在 MySQL 脚本中,您可以编写:

. . .
     set view_count = (@q := view_count+1)
. . .

这也将为您提供您正在寻找的变量。

于 2013-05-23T01:30:08.233 回答