I'm new to MySQL. I am creating a checkout page in PHP. When the users select the items they want to buy and click "Add to Cart", a temporary table gets created which has the following fields (table name is temp):
+--------------+-----------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+-----------+------+-----+-------------------+----------------+
| Cart_Item_ID | int(11) | NO | PRI | NULL | auto_increment |
| Item_ID | int(11) | NO | | | |
| Added_On | timestamp | YES | | CURRENT_TIMESTAMP | |
+--------------+-----------+------+-----+-------------------+----------------+
I'm only inserting to the Item_ID field which contains the ID of each item they bought (I'm populating the forms with item IDs). What I want to do is look up the item's name and price that's stored in the Inventory table. Here's how that looks:
+--------------+----------------+------+-----+-------------------+----------------+
| Field | Type | Null | Key | Default | Extra |
+--------------+----------------+------+-----+-------------------+----------------+
| Inventory_ID | int(11) | NO | PRI | NULL | auto_increment |
| Item_Name | varchar(40) | NO | | | |
| Item_Price | float unsigned | NO | | 0 | |
| Added_On | timestamp | YES | | CURRENT_TIMESTAMP | |
+--------------+----------------+------+-----+-------------------+----------------+
So how would I pull out the Item_name and Item_Price fields from the Inventory table based on the Item_ID field from the temp table so I can display it on the page? I just don't understand how to formulate the query. I'd appreciate any help. Thank you.
It's called JOIN
- read more here
SELECT Inventory.Item_Name, Inventory.Item_Price
FROM Inventory, temp WHERE Inventory.Inventory_ID = temp.Item_ID
what i understand is that the Item_ID in temp table is referencing to the Inventory_ID in inventory table. based on this assumption you can use the following query.
Select Item_Name, Item_Price from Inventory, Temp where Temp.Item_ID == Inventory.Inventory_ID
i guess this is what you want to do.
Thanks
As it stands, you can't (unless Inventory_ID = Item_ID)
What you need is a way of JOINing the two tables together. In this instance, if Inventory_ID = Item_ID then the following is possible:
SELECT Item_Name,
Item_Price
FROM InventoryTable
INNER JOIN TempItemTable ON (InventoryTable.Inventory_ID = ItemTable.Item_ID)
If you want to filter for a particular item you can add the constraint:
WHERE ItemTable.Item_ID = 27 --for example
That will join all the rows in your inventory table with matching rows in the Item table.
Jeff Atwood has a great (IMO) visual explanation of how JOINs work.
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.