【问题标题】:how to insert many rows without using loop from server side如何在不使用服务器端循环的情况下插入多行
【发布时间】:2018-12-27 07:45:03
【问题描述】:

我有一个用户表和通知表

我想为具有 (admin)

角色的每个用户插入通知

如何使用 SQL 命令执行此操作?没有循环和来自服务器端的 (insert) 命令

 SELECT id.users FROM users
 , (
INSERT INTO `notifications` (`id`, `note`, `link`, `type`, `object_id`, `user_id`, `status`, `status_2`, `user`, `date`) VALUES (NULL, '', '', '', '', id.user , '', '', '', '');

)

WHERE user_role.users = "admin"

ps:我正在使用 CodeIgniter

我试过了,但语法错误

【问题讨论】:

  • 好吧,如果这样做比你做错了,只需创建另一个通知表,管理员有任何通知就显示它,它可以像这样id|notification-bla|type|admin-id 现在类型可以是管理员,常规等,
  • insert into notifications select (NULL, '', '', '', '', id.user , '', '', '', '') from users where user_role.users = 'admin' 有什么问题?
  • codeigniter.com/userguide3/database/… 向下滚动到批量插入。这会给你更好的主意

标签: php sql codeigniter mysqli


【解决方案1】:
$this->db->insert_batch()

根据您提供的数据生成插入字符串,并运行查询。您可以将数组或对象传递给函数。下面是一个使用数组的例子:

$data = array(
        array(
                'title' => 'My title',
                'name' => 'My Name',
                'date' => 'My date'
        ),
        array(
                'title' => 'Another title',
                'name' => 'Another Name',
                'date' => 'Another date'
        )
);

$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')

对于大型数组或批处理,您可以将数据分成如下块:

$chunks = array_chunk($data, 500);

foreach ($chunks as $key => $chunk) {
    $this->db->insert_batch('table', $chunk);
}

【讨论】:

  • bravo!,这当然可以,但如果用户有 20,000 人呢?
  • @NullPoiиteя 你可以使用 array_chunk($data, 500);对于大批量。
  • 那么最终会循环吗? :D
【解决方案2】:

您可以尝试创建一个插入语句并结合您的表中的一个 select 语句(您非常接近 - 但语法错误) - 尝试以下操作

$this->db->query("
    INSERT INTO `notifications` (`note`, `link`, `type`, `object_id`, `user_id`, `status`, `status_2`, `user`, `date`)
    SELECT '' AS note, '' AS link, '' AS type, '' AS object_id, id, '' AS status, '' AS status_2, '' AS user, '' AS date  FROM users WHERE user_role.users = 'admin'
");

我假设您的通知表中的 id 字段是自动递增的 - 所以我忽略了它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-11-29
    • 1970-01-01
    • 2015-10-17
    • 2017-01-20
    • 2021-08-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多