开发者

mySQL DB: Making simultaneous entries?

开发者 https://www.devze.com 2022-12-16 02:39 出处:网络
Consider the following tables for a LMS: Item ( ID BIGINT NOT NULL UNIQUE AUTO_INCREMENT, ConnectLog BIGINT NOT NULL,

Consider the following tables for a LMS:

   Item (   
        ID BIGINT NOT NULL UNIQUE AUTO_INCREMENT,
        ConnectLog BIGINT NOT NULL,
        ItemClass BIGINT NOT NULL,
        ItemType BIGINT NOT NULL,
        AcqDate TIMESTAMP NOT NULL DEFAULT NOW(),
        Vendor BIGINT NOT NULL,
        Cost DECIMAL(64,2) NOT NULL DEFAULT '0.00',
        Image VARCHAR(255),
        Access INTEGER NOT NULL,
        Notes VARCHAR(255),
        PRIMARY KEY (ID)
    )

 Book   (   
        ID BIGINT NOT NULL UNIQUE AUTO_INCREMENT,
        Item BIGINT NOT NULL UNIQUE,
        ISBN BIGINT,
        Title VARCHAR(255) NOT NULL,
        Authors VARCHAR(255),
        Publisher VARCHAR(255),
        DDC VARCHAR(255),
        PubDate DATETIME,
        Edition VARCHAR(255),
        BookCase VARCHAR(255),
        Shelf VARCHAR(255),
     开发者_StackOverflow中文版   PRIMARY KEY (ID)
    )   

Now when a user makes an entry for Book, first an entry for Item has to be created first. But i need to find the ID for the Item entry that was created so i can use that value for Item in the Book table...

How? :/


Use mysql_insert_id()

// Create Entry
$sql = "INSERT INTO TABLE () VALUES()";
mysql_query($sql);
$id = mysql_insert_id();

// Create Book
$sql = "INSERT INTO TABLE (`Item_ID`) VALUES(".$id.")";
mysql_query($sql);

I bet there is a MySQL Command you could use to do it in a single query. But, this works.


According to this link, you could do an SQL query like:

INSERT INTO foo (auto,text) VALUES(NULL,'text'); # generate ID by inserting NULL
INSERT INTO foo2 (id,text) VALUES(LAST_INSERT_ID(),'text'); # use ID in second table

I haven't tested it, but it seems as though LAST_INSERT_ID() contains the last inserted ID, no matter what table it was inserted into.

If you're worried about heavy loads, and LAST_INSERT_ID() not containing the appropriate entry's ID, you could wrap these SQL statements in a transaction.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号