質問

I have a problem with a sqlite command. I have a table with three columns: Id, user, number. The id is continuing. Now if I put a user and a number inside my list, my app should compare if such a user with this number already exist. The problem is, if I use a standard "insert or ignore" command, the Id column is not fixed, so I will get a new entry every time. So is it possible just two compare two of three columns if they are equal? Or do I have to use a temporary list, where are only two columns exist?

役に立ちましたか?

解決

The INSERT OR IGNORE statement ignores the new record if it would violate a UNIQUE constraint. Such a constraint is created implicitly for the PRIMARY KEY, but you can also create one explicitly for any other columns:

CREATE TABLE MyTable (
    ID integer PRIMARY KEY,
    User text,
    Number number,
    UNIQUE (User, Number)
);

他のヒント

You shouldn't use insert or ignore unless you are specifying the key, which you aren't and in my opinion never should if your key is an Identity (Auto number).

Based on User and Number making a record in your table unique, you don't need the id column and your primary key should be user,number.

If for some reason you don't want to do that, and bearing in mind in that case you are saying that User,Number is not your uniqueness constraint then something like

if not exists(Select 1 From MyTable Where user = 10 and Number = 15) 
  Insert MyTable(user,number) Values(10,15) 

would do the job. Not a SqlLite boy, so you might have to rwiddle with the syntax and wrap escape your column names.

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top