简体   繁体   中英

How can I create a value from two other values in the same table in my SQL?

I have a table named "orders" in an SQL database:

id  date   name  orderID
========================
1   1502   John    ?
2   1502   Jane    ?

The "id" is set to AUTO_INCREMENT and the "date" is created when I insert data via my php form:

if ( !empty($_POST)) {
        $name = $_POST['name'];
        $valid = true;


        if ($valid) {
            $pdo = Database::connect();
            $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
            $sql = "INSERT INTO orders (name,date) values(?,CURDATE())";
            $q = $pdo->prepare($sql);
            $q->execute(array($name));
            Database::disconnect();
        }
}

I wish that the value for "orderID" is created automatically from the values "id" and "date":

id  date   name  orderID
========================
1   1502   John    15021
2   1502   Jane    15022

Due to the fact, that the id is an AUTO_INCREMENT you have no hand on this value. But it's quite simple. Add a AFTER INSERT trigger to the table and let it update the orderID column afterwards.

Here a quick example of a AFTER UPDATE trigger.

CREATE TRIGGER yourTrigger
AFTER INSERT
   ON yourTable FOR EACH ROW

BEGIN
    UPDATE yourTable
    SET orderid = CAST(date as char(4)) + CAST(id as char(1))
    WHERE ID = NEW.id

END; 

try

    if ($valid) {
        $pdo = Database::connect();
        $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
        $sql = "INSERT INTO orders (name,date) values(?,CURDATE())";
        $q = $pdo->prepare($sql);
        $q->execute(array($name));

        $q = $pdo->prepare( '
             update orders
             set orderId = id
             where id = SELECT LAST_INSERT_ID()'
        );
        $q->execute();          

        Database::disconnect();
    }

should work now

SET @last_id_in_table1 = LAST_INSERT_ID();
INSERT INTO orders (name,date,orderID) values(?,CURDATE(),@last_id_in_table1 )

Don't create another column in your database to hold this value, it's just duplicated data and will only serve to take up unnecessary space.

When you are retrieving data you can use CONCAT(id, date) AS orderid to get the concatenated value.

For example, to get all orderids for John:

SELECT CONCAT(id,date) AS orderid from `orders` WHERE `name`="John"

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