当它们在PHP中连续时,两个MySQLi查询是连续的(即使有多个主机)?

时间:2017-01-07 08:50:29

标签: php mysql mysqli

如果我的数据库中存在某个值组合,我需要检查。

因此我运行以下查询:

带有绑定SELECT status FROM friendships WHERE (userA = (?) AND userB = (?)) OR (userA = (?) AND userB = (?)))的

("iiii", $x, $y, $y, $x

如果结果计数为0,我想在表格中INSERT

是否有可能在这两个查询之间更改数据库,以便不满足第一个条件但仍然运行INSERT查询?

我特别感兴趣,因为我将来可能会使用多台主机。

我认为INSERT INTO .. ON DUPLICATE KEY..无法正常工作,因为我想检查没有特定订单的价值对。

1 个答案:

答案 0 :(得分:2)

我会对这两个值强加一个订单,以保证userA < userB。然后,如果在这两个字段上添加唯一索引,则不能再输入重复项。

要强制执行订单,如果在insert语句中指定了错误的订单,您可以编写一个触发订单的触发器。

以下是设置方法:

create table friendships (
    userA int not null,
    userB int not null,
    primary key (userA, userB)
);

drop trigger if exists trg_friendships_order;
delimiter //

create trigger trg_friendships_order before insert on friendships
for each row
begin
    declare temp int; -- should be same data type as userA & userB
    if new.userB < new.userA then -- swap
        set temp := new.userB;
        set new.userB := new.userA;
        set new.userA := temp;
    end if;
end
//
delimiter /

现在,当你这样做时:

insert into friendships values (2, 1);
select * from friendships;

输出将是:

 userA | userB
-------+-------
     1 |     2

所以,如果您尝试插入以下两个中的任何一个:

insert into friendships values (2, 1);
insert into friendships values (1, 2);

您会收到主键违规行为。这种情况你可以在PHP中处理。