Php 避免跨越两列之间的重量范围?mysql

Php 避免跨越两列之间的重量范围?mysql,php,mysql,sql,Php,Mysql,Sql,我在表中有两列:amountFrom、amountTo 假设我有这些行数据: amountFrom | amountTo ----------------------- 0 15 16 30 31 50 现在我想补充三点: amountFrom | amountTo ----------------------- 15 22 (should fail, already exist (crosses range))

我在表中有两列:amountFrom、amountTo

假设我有这些行数据:

amountFrom | amountTo
-----------------------
0            15
16           30
31           50
现在我想补充三点:

amountFrom | amountTo
-----------------------
15           22 (should fail, already exist (crosses range))
18           25 (should fail, already exist)
55           76 (should pass)
如何生成正确的sql查询,该查询将针对我要插入的每一行运行,并检查范围是否可用

我试过的例子

SELECT id FROM shipping WHERE amountFrom >= 15 AND amountTo <= 22

上面的查询不返回任何行,如果它是正确的查询,则应该返回行,因为我们不希望使用15和22创建新行,因为它将跨越现有的权重范围

您不必进行三次单独的插入。至少可以使用查询中的数据一次完成所有操作

要查看哪些不重叠的select语句是:

select t2.*
from table2 t2
where not exists (select 1
                  from table1 t1
                  where t1.amountFrom <= t2.amountTo and
                        t1.amountTo >= t2.amountFrom
                 );
编辑:

如果要一次执行一行操作,并防止新行重叠,请执行以下操作:

insert into t1(amountFrom, amountTo)
    select t2.amountFrom, t2.amountTo
    from (select XX as amountfrom, YY as amountTo
         ) t2
    where not exists (select 1
                      from table1 t1
                      where t1.amountFrom <= t2.amountTo and
                            t1.amountTo >= t2.amountFrom
                     );

这将使用重叠逻辑一次插入一个步骤。

您可以使用值15和22在此处尝试:

INSERT INTO t (amountFrom, amountTo)
 SELECT 15, 22
 WHERE NOT EXISTS (SELECT 1 FROM t WHERE 22 >= amountFrom AND 15 <= amountTo);

您可以检查“受影响的行”值以查看是否实际插入了该行。

似乎需要为每列指定一个范围。因此,基本上您会问如何检查两个间隔是否重叠?你在做什么?只有一张桌子。@KarolyHorvath。我假设OP中以表格格式插入的三行实际上是第二个表格。你可能错了。无论如何我认为这是假设第二个表中没有重叠。@KarolyHorvath。我同意这就是我所说的为问题中的数据工作的意思。没有失败的例子,作为新行存在。只有一个表Gordon?
INSERT INTO t (amountFrom, amountTo)
 SELECT 15, 22
 WHERE NOT EXISTS (SELECT 1 FROM t WHERE 22 >= amountFrom AND 15 <= amountTo);