简体   繁体   中英

Mysql tables relationships / Foreign key?

I'm having a hard time figuring how to link database rows in a PHP / MySql project. My order submission script currently splits information and stores it into 2 tables.

The first one is called "Orders" and contains:

$OrderId, $CustomerName, $CustomerEmail, $OrderTotal, $OrderTaxes
//and other infos about the ORDER

The second one is called "Items" and contains all the BOUGHT products infos:

$ProductId, $OrderedQty 
//for each one and such...

It has to be this way because the "Items" table will be searched by different "departments" who will only be shown the parts of the orders they are responsible for. But they all have to get the "Orders" infos for shipping purposes.

Knowing that the "OrderId" column is a primary key generated on the "Orders" table itself, and that my INSERT TO commands are both executed at the same time, how can I link an "Order Id" column in both tables ?

Do I have to generate some random key to match them ?

If I were to use a foreign key, how would the database know which product goes with which order since they are submited at the same time ?

Or is it fast enough to INSERT in "Orders" -> SELECT $OrderID -> INSERT in "Items" ?

How does one usually do this ? Can't figure this one out.

Thanks in advance for your precious help!

The bought product info should have an extra column the bought product tables called orderid, so you know which products belong to which order. As for the inserting in to the database this depends on what you are using to execute the queries. Some query classes allow you to run multiple query statements in one go, if this is the case you could run something similar to:

INSERT INTO Orders (OrderId, CustomerName, CustomerEmail, OrderTotal, OrderTaxes) Values(...)
SET @order_id = LAST_INSERT_ID();
INSERT INTO boughtItems (OrderId,ProductId,OrderedQty) Values (@order_id, :productid_1, :name_1),(@order_id, :productid_2, :name_2),(@order_id, :productid_3, :name_3) ....

In order cases you would need to run the insert statement on orders and then obtain the primary key. Take a look at these links:

In other cases you could use a class which allows you to obtain the last inserted id. This id is connection bound so should give no issues (as long as the insert works, you are not doing multiple inserts in one query, do rollbacks or other weird stuff). In this case you would do an insert and then call a secondary function to get the inserted id. See these links:

Alternatively you could also execute 2 queries. First the insert query followed by this query:

SELECT LAST_INSERT_ID() as id;

Other related links:

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