How to create a favorites table for a food shopping system in MySQL
With the development of e-commerce platforms, more and more people are beginning to purchase ingredients and food online. A system for buying daily necessities and groceries came into being. The favorites of the grocery shopping system are one of the very important features. Users can add their favorite items to their favorites for future purchase. This article will introduce how to create the favorites table of the grocery shopping system in MySQL and give specific code examples.
First, we need to create a table named "favorites" to store favorites information. This table should contain the following columns:
The following is a specific code example to create the "favorites" table:
CREATE TABLE favorites ( id INT AUTO_INCREMENT PRIMARY KEY, user_id INT, item_id INT, created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, FOREIGN KEY (user_id) REFERENCES users(id), FOREIGN KEY (item_id) REFERENCES items(id) );
In the above code, we use the AUTO_INCREMENT keyword to set the id column as an auto-incrementing primary key. At the same time, the DEFAULT keyword is used to set the default value of the created_at and updated_at columns to the current timestamp. Finally, use the FOREIGN KEY keyword to create foreign key associations between the user_id and item_id columns with other tables.
In this table, when the user collects a product, a new record can be inserted. The following is a code example of how to insert data into the "favorites" table:
INSERT INTO favorites (user_id, item_id) VALUES (1, 2);
In the above code, we insert a collection record with user ID 1 and product ID 2 into the "favorites" table.
In addition to inserting data, we can also use other SQL statements to operate the "favorites" table, such as updating favorite records, deleting favorite records, etc. The following are some commonly used examples:
Code example for updating favorite records:
UPDATE favorites SET item_id = 3 WHERE id = 1;
Code example for deleting favorite records:
DELETE FROM favorites WHERE id = 1;
Code for querying all favorite records by user id Example:
SELECT * FROM favorites WHERE user_id = 1;
Code example to query all users who have collected the product by product ID:
SELECT * FROM favorites WHERE item_id = 2;
In summary, we can use MySQL to create the favorites table of the food shopping system, and Data insertion, modification and query operations are performed through SQL statements. In actual development, the above code can be slightly modified to meet system requirements according to specific needs.
The above is the detailed content of How to create a favorites table for a grocery shopping system in MySQL. For more information, please follow other related articles on the PHP Chinese website!