使用if条件的mysql触发器,更新父表

时间:2018-02-12 08:36:24

标签: mysql triggers

我的php文件中有这个查询,需要创建一个mysql触发器来存储mysql中的成功状态:

SELECT
SUM(IF(repstate = 0, 1, 0)) AS repstatezero,
SUM(IF(repstate = 1, 1, 0)) AS repstateone,
SUM(IF(repstate = 2, 1, 0)) AS repstatetwo,
SUM(IF(repstate = 3, 1, 0)) AS repstatethree
FROM positions 
WHERE order_id = $id 

// Snippet from PDO foreach
if(
$row['repstatezero'] == 0 AND
$row['repstateone'] == 0 AND
$row['repstatetwo'] == 0 AND
$row['repstatethree'] >= 1 ) {
echo "<span class='badge badge-success'>Success</span>";   
}

如果所有positions.repstate X都是相关参考ID位置的0,则order.state的值应设置为3.订单

这就是我所拥有的:

  DELIMITER $$

  CREATE TRIGGER update_orderstate
  BEFORE UPDATE ON positions
  FOR EACH ROW

    BEGIN

    SELECT 
    SUM(CASE WHEN repstate=0 THEN 1 ELSE 0 END) AS repstatezero,
    SUM(CASE WHEN repstate=1 THEN 1 ELSE 0 END) AS repstateone,
    SUM(CASE WHEN repstate=2 THEN 1 ELSE 0 END) AS repstatetwo,
    SUM(CASE WHEN repstate=3 THEN 1 ELSE 0 END) AS repstatestree

    FROM positions 

    ....
    END

DELIMITER ;

我坚持了下来。我尝试了一些后续的if条件但是失败了。

感谢。

参考表(子)状态=代码段中的repstate

订单:

| ID | order      | (parent)state  |
| 1  | some text  | 0              |
| 2  | some text  | 3              |
| 3  | some text  | 0              |

位置:

| ID | order_id   | (child)state   |
| 1  | 1          | 0              |
| 2  | 3          | 1              |
| 3  | 2          | 3              |
| 4  | 2          | 3              |

在这种情况下,订单ID 2也应该设置为3相关的position.id 3 + 4.

在将相同order_id的所有子状态手动设置为3(3 =已完成)后,(父)状态也应自动设置为3.

商店的另一个例子:如果所有职位都已交付,则订单已完成。

0 个答案:

没有答案