提问人:ᴍᴇʜᴏᴠ 提问时间:11/6/2023 更新时间:11/6/2023 访问量:25
在“INSERT INTO ...SELECT“查询
Mixing values in `INSERT INTO ... SELECT` query
问:
假设我想插入注释,注释表需要一个,但我只有.我不想事先在单独的查询中选择客户。customer_id
email
来自 orm/query-builder.html#inserting-data 的查询看起来正是我想要的。INSERT INTO ... SELECT
但是,如何在查询的第一部分中选择的值之外提供值呢?
我试过了:
$select = $customersTable->find() ->select(['customer_id']) ->where(['email' => '[email protected]']); $query = $this->query() ->insert(['customer_id', 'data']) ->values($select) ->values(['data' => 'test 123']) ->execute();
我得到:你不能在插入中混合子查询和数组数据
我试过了:
$select = $customersTable->find() ->select(['customer_id', '"test" AS `data`']) ->where(['email' => 'username@example']); $query = $this->query() ->insert(['customer_id', 'data']) ->values($select) ->execute();
我得到了:
Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '`` AS `Customers__"test" AS `data`` FROM `customer` `Customers` ' at line 1 INSERT INTO `comments` (`customer_id`, `data`) SELECT `Customers`.`customer_id` AS `Customers__customer_id`, `Customers."test" AS `data`` AS `Customers__"test" AS `data`` FROM `customer` `Customers` WHERE `email` = :c0
请帮忙
答:
1赞
ndm
11/6/2023
#1
子句中的自定义别名字段可以通过常规数组语法定义,其中键将用作别名。SELECT
key => value
还要确保让驱动程序引用数据,因为它将按原样插入,否则很容易发生可能的 SQL 注入!
$select = $customersTable->find()
->select([
'customer_id',
'data' => $customersTable->getConnection()->quote('test')
])
->where(['email' => 'username@example']);
另请参阅
评论
0赞
ᴍᴇʜᴏᴠ
11/9/2023
谢谢奥利弗!
评论