Вопрос

Currently, I have a SQLite database which is tracking view counts. It has columns for the views, the id of the video, and the timestamp of when the last sample was taken.

Currently, I am using (in Python):

cursor.execute("INSERT INTO view_counts VALUES (?,?,?)", (views, id, time))

How do I insert a video only if the view count is unique for a given ID?

For example, if the previous rows are:

views    id    timestamp
200      5     60
300      5     70

I want to insert the video only if the new view count is above 300. If the view count is still 300 for the given id, I don't want to insert it.

Note that I can't just ensure that the views column is unique, because a video with a different ID may have the same amount of views.

Thanks for your help!

Это было полезно?

Решение

Let the database check for uniqueness:

create table view_counts (
    views,
    id,
    time,
    unique(views,id)
) 

On this way, you get a IntegrityError, when views and id is not unique.

Другие советы

This may not be the most efficient way of doing this, but I believe it will work. First of all, select the video with the ID you want:

cursor.execute("SELECT * FROM view_counts WHERE id=?",(id))

Then, use an if statement to check the value

while True:
    row = cur.fetchone()
    if row[0] > 300:  #row[0] is the row your views should be in
        cursor.execute("INSERT INTO view_counts VALUES (?,?,?)", (views, id, time))
        break

Like I said, this is not the best way of doing it. My gut tells me that you can do somehting alone the lines of:

cursor.execute(UPDATE view_counts SET views=? WHERE views > ?", (views, old_views))

Where old_views could be the last views value that was passed in (E.g. old_views = views)

Although this code may not solve your problem fully as my sqlite isn't what it was, I hope it goes some way to fixing your problem. If you look up more about the update query you may be able to fix my slightly guess work code. As far as I can remember, SQLite3 supports the use of > but if it didn't it should be easy to develop something (as I have done in my top example) that gets the current view count.

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top