基于前一行值的MySQL约束

时间:2018-06-23 09:37:05

标签: mysql constraints check-constraint

我有2张桌子:

表A:

function reverseArray (arr) {
    var newArr = [];
    for (var i = 0; i < arr.length; i++) {      
        newArr[i] = arr[arr.length - i - 1];
    }   
    return newArr;
}
console.log(reverseArray(["A", "B", "C", "D", "E", "F"]));

表B:

AID
1
2
3
4

在将AID的状态更改为“已关闭”之前,如何限制在B表中添加另一行。 还是应该将“状态”列移至A表?但是即使如此,我怎样才能在B表中检查A行的状态?

1 个答案:

答案 0 :(得分:0)

通过演示方式:

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(BID SERIAL PRIMARY KEY
,AID INT NOT NULL
,Status VARCHAR(12) NOT NULL
);

INSERT INTO my_table VALUES
(1,1,'Open'),
(2,2,'Open'),
(3,3,'Closed');

SELECT * FROM my_table;
+-----+-----+--------+
| BID | AID | Status |
+-----+-----+--------+
|   1 |   1 | Open   |
|   2 |   2 | Open   |
|   3 |   3 | Closed |
+-----+-----+--------+

INSERT INTO my_table (aid,status) 
SELECT 1
     , 'Open' 
  FROM (SELECT 1) x 
  LEFT 
  JOIN 
     ( SELECT a.* 
         FROM my_table a 
         JOIN 
            ( SELECT aid
                   , MAX(bid) bid 
                FROM my_table 
               GROUP  
                  BY aid
            ) b
           ON b.aid = a.aid
          AND b.bid = a.bid
      ) y
     ON y.aid = 1
    AND y.status = 'Open'
  WHERE y.bid IS NULL;

+-----+-----+--------+
| BID | AID | Status |
+-----+-----+--------+
|   1 |   1 | Open   |
|   2 |   2 | Open   |
|   3 |   3 | Closed |
+-----+-----+--------

INSERT INTO my_table (aid,status) VALUES
(1,'Closed');

SELECT * FROM my_table;
+-----+-----+--------+
| BID | AID | Status |
+-----+-----+--------+
|   1 |   1 | Open   |
|   2 |   2 | Open   |
|   3 |   3 | Closed |
|   4 |   1 | Closed |
+-----+-----+--------+

INSERT INTO my_table (aid,status) 
SELECT 1
     , 'Open' 
  FROM (SELECT 1) x 
  LEFT 
  JOIN 
     ( SELECT a.* 
         FROM my_table a 
         JOIN 
            ( SELECT aid
                   , MAX(bid) bid 
                FROM my_table 
               GROUP  
                  BY aid
            ) b
           ON b.aid = a.aid
          AND b.bid = a.bid
      ) y
     ON y.aid = 1
    AND y.status = 'Open'
  WHERE y.bid IS NULL;

SELECT * FROM my_table;
+-----+-----+--------+
| BID | AID | Status |
+-----+-----+--------+
|   1 |   1 | Open   |
|   2 |   2 | Open   |
|   3 |   3 | Closed |
|   4 |   1 | Closed |
|   5 |   1 | Open   |
+-----+-----+--------+