简体   繁体   中英

pdo + sql insert select group by NOT WORKING

can someone help me with this pdo:

  • idea:

insert into 'table 1', rows obtained with a select from table 0

  • structure of table1:

    id_i (int Primary AI)| id_e (int)| date (datetime)| num (text) | sum (decimal 14,2)| stat (tinyint)

bonus question: any idea for optimazing the sql request if 1000+ rows?

my code:

$query = " INSERT INTO table1 (id_e, date, string, sum, stat)
    SELECT id_s, NOW(), GROUP_CONCAT(id_r), SUM(bud), 0
    FROM table0 as e
    WHERE e.stat=4 AND e.datetime<='$date' GROUP BY e.id_s
    ";

    try 
    {
    $bdd = new PDO('xxxx');
    }

    catch(Exception $e)
    {
    die('Erreur: '.$e->getMessage());   
    }
    $request= $bdd->prepare($query);

    if ($bdd->execute()) {
        echo 'ok';
    }
    else {
        echo 'no';
    }

As you understand I got 'no'! But if I do only the SELECT it's working!

Can you please post the error you are getting?

In 5.7 the sqlmode is set by default to

ONLY_FULL_GROUP_BY,STRICT_TRANS_TABLES,NO_ZERO_IN_DATE,NO_ZERO_DATE,ERROR_FOR_DIVISION_BY_ZERO,NO_AUTO_CREATE_USER,NO_ENGINE_SUBSTITUTION.

Remove the clause ONLY_FULL_GROUP_BY. You can remove like this:

 SET sql_mode=(SELECT REPLACE(@@sql_mode,'ONLY_FULL_GROUP_BY',''));

Please try it and see if it works for you.

If your not getting an error then turn on error reporting for debugging

$bdd = new PDO('xxxx');
$bdd->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION;

This will allow you to see what errors are coming out, but it's not good for end users to see these sorts of errors.

add the missing columns to the group-by:

INSERT INTO table1 (id_e, date, string, sum, stat)
    SELECT id_s, NOW() as tm, GROUP_CONCAT(id_r), SUM(bud), 0 AS stat
    FROM table0 as e
    WHERE e.stat=4 AND e.datetime<='$date' 
    GROUP BY e.id_s, tm, stat

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