简体   繁体   中英

INSERT and INNER JOIN MYSQL combination

I have two tables. One is 'business' structured like so:

business_id | name | linkto_category_id | business_category_description

and another one 'business_category' that holds the categories list

business_category_id | business_category_description

Now I would like to select all entries in 'business' with the corresponding 'linkto_category_id' that equals the 'business_category_id' in the 'business_category' table and then insert the 'business_category_description' into the 'business' table.

This is what I have so far...

INSERT INTO business(business_category_description)
(SELECT business_category.business_category_description, business_category.business_category_id, business.linkto_category_id
FROM business
INNER JOIN business_category
ON business.linkto_category_id=business_category.business_category_id);

Generally you shouldn't replicate data you can access with an inner join into a another table. You use the inner join to get the description from the category each time you get the business.

Normalising your data is usually done to prevent things getting out of date and to minimise the amount of data you are storing.

Using the linkto_category_id allows you to retrieve the description every time you need it without having to store a big identical text field in each business row.

As Brody commented, it was an update that was needed.

Used top answer from here: How can I do an UPDATE statement with JOIN in SQL?

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