sql to populate newly created link table - mysql

I would be really grateful if somebody could help me out with this..
I actually have 2 tables in my database: books and authorlist.
The book table contains a field 'book_aut' which contains the foreign key of the authorlist table.
The authorlist table has only 2 fields, the primary key and the 'authors' column which contains a list of names.
I have to modify the table structure so that books table is linked to an authors table via a link table called 'lnk_book_author'
So my first task is to create a new table called 'authors' which contains 3 fields - primary id, name, surname, which i already did.
Next, i created the link table called 'lnk_book_author' and this one contains 3 fields, the primary id, book_fk, author_fk. The book_fk and author_fk refer to the id of the book and author respectively.
My problem is that i have more than 6000 entries in the books table and i would like to know how to populate the link table with the book id and the author id.
Is there a way of doing that using sql instead of manually populating the lnk_book_author table.
Hope i was clear enough..
Thanks a lot for any suggestion provided.

I'm infering the IDs already in your new [authors] table mean nothing with regards to the old tables. If that's the case you need to relate the records by the Name. And there I need to assume that the names are entered Identically. If they're not, it may not be possible to do. We'd need to know a lot more specifics to be sure...
INSERT INTO
lnk_book_author
SELECT
Books.PrimaryKeyFieldName,
Authors.PrimaryKeyFieldName
FROM
Books
INNER JOIN
AuthorList
ON Books.BookAut = AuthorList.PrimaryKeyFieldName
INNER JOIN
Authors
ON CONCAT(',', AuthorList.Authors, ',') LIKE CONCAT('%,', Authors.Name, ',%')

Something like that ?
INSERT INTO lnk_book_author(book_fk,author_fk)
SELECT b.book_id,a.author_id
FROM books b INNER JOIN authorlist a
ON b.book_aut=a.author_id

Try this it should work:
INSERT INTO lnk_book_author (book_fk, author_fk)
VALUES ((SELECT Id FROM books), (SELECT Id FROM authors))
And by the way there's no point having an Id column in the lnk_book_authors table, you may as well just make the foreign keys a composite primary key.
UPDATE
Sorry I realise that would only work with one record, try the following SQL:
INSERT INTO lnk_book_author (book_fk, author_fk)
SELECT books.Id, authors.Id
FROM books, authors

Related

What is an elegant solution to ensure inserts are limited to the root ownership in a hierarchical tree in MySQL?

So I have the following hierarchical database structure:
Table person has columns id and some other fields.
Table car has columns id, owner (with a foreign key constraint to person.id) and some other field
Table bumpersticker has columns id, car (with a foreign key constraint to car.id) and some other fields
I want to INSERT a row in to bumpersticker and have values to populate the row. I also have a person.id value of the person trying to add the bumpersticker.
What is the best practice to ensure that the car.owner value selected from the bumpersticker.car is in fact the same person.id as I have?
I guess one obvious way is to first execute a select query, on the car table and select the car.owner and validate that this value is the same value as the id of the person trying to add the bumpersticker and then execute an insert query.
but this seems like something there must be an elegant solution to in MySQL. at least not having to do two separate queries.
Most thankful for your help!
You can insert from a SELECT query that tests if the owner matches the criteria
INSERT INTO bumpersticker (car, sticker_text)
SELECT c.id, "If you can read this you're too close"
FROM car AS c
WHERE c.id = #car_id AND c.owner = #person_id
#car_id is the ID of the car you're adding the bumpersticker for, and #person_id is the ID of the user doing the insert. If the owner ID doesn't match, the SELECT query will return no rows, so nothing gets inserted.
DEMO

Any simple way to set one primary key as a foreign key to multiple tables

I have one table
program(p_id(pk), program_name)
and three other tables:
graduate_survey(id(pk),PO1_avg,PO2_avg,program_name,session),
alumni_survey(id(pk),PO1_avg,PO2_avg,program_name,session),
faculty_survey(id(pk),PO1_avg,PO2_avg,program_name,session)...
I have to link the three tables with program table...How to link these tables in MySQL? graduate_survey, alumni_survey, faculty_survey are some forms which is calculated for some specific program...If in the forms graduate_survey, alumni_survey, faculty_survey there is no text box for entering the program_name, but if i made a column name 'program_name' in the database tables, can i enter the program_name by referencing to the program table? Is there will be any join query?
Use the program id as foreign key in the other tables, like so:
program(p_id(pk), program_name)
graduate_survey(id(pk),PO1_avg,PO2_avg,p_id(fk),session),
alumni_survey(id(pk),PO1_avg,PO2_avg,p_id(fk),session),
faculty_survey(id(pk),PO1_avg,PO2_avg,p_id(fk),session)
You don't really need the program name for the sake of the FK constraints but it's still a nice to have at some point, maybe.
This way you can easily join based on p_id, for instance:
"SELECT * FROM program INNER JOIN graduate_survey ON program.p_id=graduate_survey.p_id WHERE <your condition here>"
Hope this helps.

MYSQL Move data from one table column to another table column if condition is matched

i'm not really an mysql guy more like a php guy :)
I have an issue with copying values from one table column to another table column.
The trick is that the data should be copied only if condition is matched. So basically i want to transfer categoryID from one table to another if postIDs are the same.
i have two tables news and news_in_category
in news table i have the following columns (id, title, categoryID)
in news_in_category i have the following columns (newsId, newsCategoryId)
So i want to move newsCategoryId to categoryID if newsId is the same as id.
For example if news table id=99 it should look up in news_in_category table find the newsId with value 99 and copy the newsCategoryId value to news table categoryID with id 99
Hope it makes sense to you :)
Thank you!
Try:
UPDATE news n
JOIN news_in_category nic ON n.id = nic.newsId
SET n.categoryID = nic.newsCategoryId
It looks like you might have a redundant functional dependency: newsId -> categoryId. If so, you could drop the news_in_category table without any loss of information, after running the query above.

multiple column values in mysql

I need to make a table 'Movies' which will have columns:
ID Title Description Category etc
And another one called 'Movie_Categories' containing, for example
ID Category
1 Action
2 Adventure
3 Triller
but since category in table Movies will have multiple choices what is the correct way to do this?
should i use comma-separated values like someone said in this post Multiple values in column in MySQL or is there a better way?
This is a many-to-many relationship.
You need a join table to make it right, such as :
CREATE TABLE film_category (
category_id int,
film_id int,
PRIMARY KEY (category_id, film_id)
);
DO NOT GO FOR COMMA-SEPARATED VALUES. NEVER.
Having said that. Bear in mind that when you have a so called many-to-many relationship, that is, a relationship where you can have one category with many movies and one movie with many categories, you will always need to generate an additional table.
This table will only need the Primary Keys of each of the other 2 tables and will have a compound key.
So the schema will end up being:
Movies(ID, Title, Description, Category)
Categories(ID, Category)
Movies_Categories(ID_Movie, ID_Category)
In bold are the primary keys.
In order to get all the categories for a movie you will just have to join each of the three tables.
A final comment about having multi-valued fields is that your table will not be in First Normal Form which will, sooner or later, give you lots of headaches.
The last thing to do is have a non normalized table by storing comma separated values.
*You should have a table movies and a table for categories.
You should create a mapping table which will map the movieId to the categoryId*

having trouble with foreign key queries

I'm new to SQL and I'm having a hard time figuring out how to execute queries with foreign keys on MySQL Workbench.
In my example, I have three tables: people, places, and people_places.
In people, the primary key is people_id and there's a column called name with someone's name.
In places, the primary key is places_id and there's a column called placename with the name of a place.
People_places is a junction table with three columns: idpeople_places (primary key), people_id (foreign key), and places_id (foreign key). So this table relates a person to a place using their numerical IDs from the other two tables.
Say I want the names of everyone associated with place #3. So the people_places table has those associations by number, and the people table relates those numbers back to the actual names I want.
How would I execute that query?
Try this to find all the people names who are associated with place id 3.
SELECT p.name
FROM people as p
INNER JOIN people_places as pp on pp.people_id = p.people_id
WHERE pp.places_id = 3
OK, so you need to "stitch" all three tables together, yeah?
Something like this:
select people.name
from people -- 1. I like to start with the table(s) that I want data from, and
, people_places -- 2. then the "joining" table(s), and
, places -- 3. finally the table(s) used "just" for filtering.
where people.people_id = people_places.people_id -- join table 1 to table 2
and people_places.place_id = places.place_id -- join table 2 to table 3
and places.name = "BERMUDA" -- restrict rows in table 3
I'm sure you can do the rest.
Cheers. Keith.