简体   繁体   English

Mysql 查询仅在选择计数 > n 时插入

[英]Mysql query insert into only if select count > n

I have 2 queries:我有两个疑问:

SELECT COUNT(*) FROM a WHERE id = 1
//if row == 1
INSERT INTO a VALUES(fielda) VALUES('value')

Is there a way to merge these two queries into one?有没有办法将这两个查询合并为一个? I tried with 'IF (count> 0, ..)' and similar, but the query is incorrect.我尝试了 'IF (count> 0, ..)' 和类似的,但查询不正确。 This involves inserting a new record into the table, taking care not to exceed a pre-set number of records for each field.这涉及向表中插入新记录,注意不要超过每个字段的预设记录数。 In theory it should be similar to an INSERT IF ...理论上它应该类似于 INSERT IF ...

Edit:编辑:

@Barmar I tried but I think I did not understand what you wrote (in fact I made a mistake in the query), I try to answer like this: @Barmar 我试过了,但我想我不明白你写了什么(实际上我在查询中犯了一个错误),我试着这样回答:

THE QUERY AFTER YOUR RESPONSE:
INSERT INTO table1 SELECT MAX(id) FROM table1 WHERE field1 = (SELECT id from a WHERE f = field2) HAVING COUNT(*) = 1 (all fields request) VALUES (all values request)

//field1 = id from table2
//field2 = id from another table: associative value

//ORIGINAL QUERY
//FIRST COUNT:
SELECT COUNT(*) from table1 WHERE field1 = (SELECT id FROM table2 WHERE f = field2)
//AFTER THE INSERT:
INSERT INTO table1 (all fields request) VALUES (all values request)

I came to mind this example I try to show you:我想到了这个我试图向你展示的例子:

TABLE PLAYER: fields(ID, TEAMID, NAME) => (id=int, teamid=int associate to table team, name=varchar)表球员:fields(ID, TEAMID, NAME) => (id=int, teamid=int 关联表队, name=varchar)

TABLE TEAM: fields(ID NAME) => (id=int, name=varchar)表队:字段(ID NAME)=>(id=int,name=varchar)

Suppose that the players in a team are maximum 20, so you expect maximum 20 records associated by the player table for the same teamid value, or at least this is what we humans think, because for the computer can also be infinite.假设一个团队中的玩家最多为 20,因此您期望玩家表关联的最多 20 条记录为相同的 teamid 值,或者至少这是我们人类的想法,因为对于计算机来说也可以是无限的。 I was looking for a way to allow the insertion only in the case in which it is actually permissible to insert records, in this case the condition is that in the players table there are less than 21 records per team.我一直在寻找一种方法,仅在实际上允许插入记录的情况下才允许插入,在这种情况下,条件是在玩家表中每支球队的记录少于 21 条。

You can use INSERT ... SELECT , and put the condition in the SELECT query.您可以使用INSERT ... SELECT ,并将条件放在SELECT查询中。

INSERT INTO player (teamid, name)
SELECT @teamid, @playername
FROM DUAL
WHERE (SELECT COUNT(*) FROM player
        WHERE teamid = @teamid) < 20

DUAL is a dummy table when you need to select literal data, but need to include other clauses in the query.当您需要选择文字数据但需要在查询中包含其他子句时, DUAL是一个虚拟表。

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

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