Mysql 在条件插入时崩溃

Mysql crashed on conditional insert

我需要一些关于插入语句的条件来防止未经授权的插入。 我写了这样的东西:

INSERT INTO `fund` (amount,description)
    SELECT 1000,'Some description'
    WHERE 12 IN (SELECT id FROM users WHERE allow_add=1)

其中12是当前用户的id。 但是 mysql 进程意外停止! 我使用 XAMPP 和 MySQL 版本:5.5.5-10.1.13-MariaDB。 请注意,我在 运行 之前的这段代码在 SQL 服务器中没有任何问题。 有什么想法吗?

在您的查询中添加分号 (;),以及 desc 在查询中的作用。它将描述 table 结构及其属性。

这不是授权在数据库中插入的正确方法。相反,您可以使用基于编程的解决方案来解决此问题。

在PHP中,正确的解决方案可能是:-

if ($user->allow_add == 1){ //where $user is the User instance for current user
    $sql->query("INSERT INTO `fund` (amount,desc) VALUES(1000,'Some desc')");
}

试试这个:

INSERT INTO `fund` (amount,desc)
SELECT 1000 as amt,'Some desc' as des FROM users WHERE allow_add=1 LIMIT 12

来自用户和 Where exists 工作所以可能是 in?

MariaDB [sandbox]> delete from t where att = 3;
Query OK, 2 rows affected (0.04 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> select * from t;
+------+------+
| id   | att  |
+------+------+
|    1 |    1 |
|    1 |    2 |
|    2 |    0 |
+------+------+
3 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> insert into t(id,att)
    -> select 4,3
    -> from users
    -> where id = 1;
Query OK, 1 row affected (0.05 sec)
Records: 1  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]>
MariaDB [sandbox]> select * from t;
+------+------+
| id   | att  |
+------+------+
|    1 |    1 |
|    1 |    2 |
|    2 |    0 |
|    4 |    3 |
+------+------+
4 rows in set (0.00 sec)

MariaDB [sandbox]>
MariaDB [sandbox]> insert into t(id,att)
    -> select 4,3
    -> where exists (select 1 from users where id  = 1);
Query OK, 1 row affected (0.02 sec)
Records: 1  Duplicates: 0  Warnings: 0

MariaDB [sandbox]>
MariaDB [sandbox]> select * from t;
+------+------+
| id   | att  |
+------+------+
|    1 |    1 |
|    1 |    2 |
|    2 |    0 |
|    4 |    3 |
|    4 |    3 |
+------+------+
5 rows in set (0.00 sec)

感谢 ,我找到了解决方案。与 SQL 服务器不同,MySQL 似乎需要条件 SELECT 中的 FROM 语句。所以,我添加了一个临时 table 名称,如下所示:

INSERT INTO `fund` (amount,description)
SELECT 1000,'Some description'
FROM (SELECT 1) t
WHERE 12 IN (SELECT id FROM users WHERE allow_add=1)