简体   繁体   中英

MySQL: Iteratively insert a record if not exists

I have a huge table like this,

user_id    item     value
      1      aa         1
      1      bb         0
      1      cc         0
      2      aa         1
      2      bb         1
      2      cc         1
      2     xxx         1
      3      aa         0
      3      bb         0
      3      cc         0
    ...     ...       ...

I want to insert a record like this

{user_id}     xxx     0

for all the users if they don't have this 'xxx' record. Is it possible to do this in SQL?

The basics of what you are asking for are suitable for an NOT EXISTS check, to start you off, you can select the user's who do not have that entry as follows.

SELECT DISTINCT u1.user_id
FROM yourUserTable u1
WHERE NOT EXISTS (SELECT 1 FROM yourUserTable u2 WHERE u2.item='xxx' and u2.user_id = u1.user_id)

From that you can then construct your insert statement.

INSERT INTO youUserTable (user_id, item, value)
SELECT etc

If there was a unique key on the user_id / item then there are some alternative options.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM