使用两列避免交叉重量范围BETWEEN? MySQL的

时间:2014-02-02 18:18:25

标签: php mysql sql

我在表amountFrom中有两列:amountToshipping

假设我有这些行数据:

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的新行,因为它将跨越现有的权重范围

2 个答案:

答案 0 :(得分:1)

你可以尝试这个(这里有值15和22):

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

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

答案 1 :(得分:0)

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

用于查看哪些不重叠的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作为

insert into t1(amountFrom, amountTo)
    select t2.amountFrom, t2.amountTo
    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
                     );

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