简体   繁体   English

如果数据记录不存在,则将其存储到另一个表中

[英]Store a data record into another table if it does not exist

I am looking for a SQL code that is doing the following thing: 我正在寻找一个执行以下操作的SQL代码:

  1. SELECT * FROM fzs_contest WHERE answer = 'D' order by rand() limit 1;
  2. Store the result of the code above to the table fzs_contest_winners (create the table if it does not exist) 将上面代码的结果存储到表fzs_contest_winners中 (如果表不存在则创建表)
  3. If the data record already exists in the table fzs_contest_winners , reapeat line #1 until it is unique. 如果数据记录已经存在于表fzs_contest_winners中 ,请重新排列第1行,直到它是唯一的。

Is that possible with SQL only? 这只能用SQL吗?

How about just getting a valid winner the first time? 如何才能第一次获得有效的赢家?

insert into fzs_contest_winners ( . . .)
    select . . . 
    from fzs_contest c
    where answer = 'D' and
          not exists (select 1 from fzs_context_winners cw where cw.?? = c.??)
    order by rand()
    limit 1;

The ?? ?? is for the column that identifies someone as being the same in the two tables. 用于标识两个表中某人相同的列。

Note: This type of query could choose the same winner twice, if two threads were running at the same time. 注意:如果两个线程同时运行,则此类型的查询可以选择相同的获胜者两次。 However, it seems unlikely to me that you are selecting more than one winner at a time. 但是,我似乎不太可能一次选择多个获胜者。 In addition, you should guarantee that a person only appears once in the table by using a unique index. 此外,您应该保证一个人只使用唯一索引在表中出现一次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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