简体   繁体   中英

Symfony2 MySQL: INSERT SELECT syntax error

I am having problems with writing correct MySql query. I want to insert new collection for every user with id higher than 1000 but less than 10000.

$conn = $this->em->getConnection();

$stmt = $conn->prepare('INSERT INTO collection (name, type) 
                   values(:name, :type) 
                   SELECT  * FROM user WHERE id<:endUser AND id>:startUser');
$stmt->bindValue('name', 'Default');
$stmt->bindValue('type', 0);
$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();

This what I tried to write, but I get syntax error. Please explain me how to correct query

UPD

I should have given detailed structure of tables.

Collection

  CREATE TABLE IF NOT EXISTS `collection` (
         `id` int(11) NOT NULL AUTO_INCREMENT,
         `user_id` int(11) NOT NULL,
         `name` varchar(255) COLLATE utf8_unicode_ci NOT NULL,
         `type` smallint(6) NOT NULL,
          PRIMARY KEY (`id`),
          KEY `IDX_FC4D6532A76ED395` (`user_id`)
          );

User

   CREATE TABLE IF NOT EXISTS `user` (
         `id` int(11) NOT NULL AUTO_INCREMENT,
         `username` varchar(255) NOT NULL,
          PRIMARY KEY (`id`)
          );

User has one-to-many relationship with Collection.

With a SELECT INTO you have to select the values you want to place in the new row and only those values . And you dont use the VALUES() clause.

As you are using static values for the new rows and not values from the user table you can do it like this.

Oh and I see in your edit you were using the wrong table name It should have been fos_user

Also as fos_user.user_id is a NOT NULL field you need to include that column in the list of fields in the insert.

$conn = $this->em->getConnection();

$stmt = $conn->prepare('INSERT INTO collection (user_id, name, type) 
                              SELECT id, 'default', 0
                              FROM fos_user
                              WHERE id > :startUser AND id < :endUser');

$stmt->bindValue('startUser', 1000);
$stmt->bindValue('endUser', 10000);
$stmt->execute();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM