Join statement with multiple conditions - mysql

Ok I have two mysql table one called books and the other reading_tracking.
I have written the join query below:$query = "SELECT * FROM books inner join reading_tracking on book_num = book_id;
My dilemma is that i don't want all the from books i want a query which in theory would look something like this:
"SELECT * FROM books
where reading_status = 1 inner
join SELECT * FROM reading_tracking
on book_num = book_id";
If i try this as suggested:
SELECT * FROM books b
INNER JOIN reading_tracking rt
ON b.book_id = rt.book_num
WHERE rt.reading_status = 1;
The thing is in my program not all books in books table are in reading_tracking, user have to make an additional step, so i don't want books that are similar in both tables i want all the books from books where reading_status = 1; but want all the books from reading_tracking.

Your syntax should have the SELECT [x] FROM followed by the INNER JOIN, and then you need an ON to denote which field is synonymous between the two tables. In your example, I'm assuming you have a column book_id in books, and a column book_num in reading_tracking.
The WHERE clause should come after the ON, and additionally should specify which of the two tables you want to look for the column in.
This can be seen in the following:
SELECT * FROM books b
INNER JOIN reading_tracking rt
ON b.book_id = rt.book_num
WHERE rt.reading_status = 1;
This will search books for any row that has a reading_status of 1 in the reading_tracking table.

I assume column book_num is from books table, column book_id is from reading_tracking table. First join the 2 tables then use WHERE to filter the condition:
SELECT * FROM books b
INNER JOIN reading_tracking r
ON b.book_num = r.book_id
WHERE b.reading_status = 1;

You can use a subquery before doing the JOIN as shown below:
SELECT *
FROM (SELECT * FROM books WHERE reading_status=1) A
INNER JOIN reading_tracking B on B.book_num=A.book_id;
See Using MySQL Alias To Make The Queries More Readable

Related

MYSQL: Select Query with multiple values from one column

i am currently working with a MYSQL-Database whichhas three tables:
Books, Keywords and KeywordAssignment.
The tables Books and Keywords are in a many to many relationship therefore the table KeywordAssignment.
Now to my question: I want to search for a book with multiple (max: up to ten) keywords.
I've already tried a self join:
SELECT BookID
FROM Keywords K1 INNER JOIN
Keywords K2
ON K1.KeywordAssignmentID=K2.KeywordAssignmentID INNER JOIN
KeywordAssignment
ON KeywordAssignment.KeywordAssignmentID=K1.KeywordAssignmentID INNER JOIN
Books
ON KeywordAssignment.BookID=Books.BookID
WHERE K1.Keyword='Magic' AND K2.Keyword='Fantasy'
The problem is it only works if the given Keyword are in the right order. If they aren't there are more than one.
I appreciate your help thank you very much!
You need to GROUP BY BookID and a HAVING clause with the condition that both keywords are linked to that BookID:
SELECT b.BookID, b.Title
FROM Books b
INNER JOIN KeywordAssignment ka ON ka.BookID = b.BookID
INNER JOIN Keyword k ON k.KeywordID = ka.KeywordID
WHERE k.Keyword IN ('Magic', 'Fantasy')
GROUP BY b.BookID, b.Title
HAVING COUNT(DISTINCT k.Keyword) = 2
This code will return books that are linked to both 'Magic' and 'Fantasy'.
If you want either of the 2 keywords then remove the HAVING clause.
If I understand your question correctly, you want to query for books that have multiple key words. The key word there is have. I don't have MYSQL but the query should look something like this:
SELECT B.BookID, COUNT(*) as NumberOfKeywords FROM Books B
INNER JOIN KeywordAssignment KA
ON B.BookID = KA.BookID
INNER JOIN Keywords K
ON KA.KeywordID = K.KeywordID
GROUP BY B.BookID
HAVING NumberOfKeywords > 0 AND NumberOfKeywords <= 10
What we are doing is grouping by each book and then selecting the ones that have more than 0 keywords and less than 10.

Mysql query to join two tables using many to many relation

I have three tables called Notes another table called Tags and third as a Join table called NoteTagsJoin, Join table holds two foreign keys primary Note id and Primary Tag id. I use this query to get all Notes with tagId:
SELECT * FROM notes INNER JOIN note_tag_join ON notes.entryId = note_tag_join.noteId WHERE note_tag_join.tagId =:tagId
And this query to get all Tags:
SELECT * FROM tags INNER JOIN note_tag_join ON tags.tagId = note_tag_join.tagId WHERE note_tag_join.noteId =:noteId
How can I get Note and all its tags using just Note id with one query?
Are you looking for two joins?
SELECT n.*, t.*
FROM notes n INNER JOIN
note_tag_join nt
ON n.entryId = nt.noteId INNER JOIN
tag t
ON t.tagId = nt.tagId
WHERE n..entryId = :noteId
SELECT * FROM table_name
LEFT JOIN table_name2 ON table_name.id = table_name2.id
LEFT JOIN table_name3 ON table_name2.id = table_name3.id
WHERE table_name.id = id;
Change the "id" with the appropriate id's that you're using. It's important that the id's in the JOINs are coherent, else there will be no link between them.
If you want to select fields of the 3 tables, do this:
SELECT (fields that you want to show) FROM tableA
INNER JOIN tableB ON tableA.commonField = tableB.commonField
INNER JOIN tableC ON tableB.commonField = tableC.commonField

SQL Join involving 3 tables, how to?

SQL newbie here.
So we have 3 tables:
categories(cat_id,name);
products(prod_id,name);
relationships(prod_id,cat_id);
It is a one-to-many relationship.
So, given a category name say "Books". How do I find all the products that come under books?
As an example,
categories(1,Books);
categories(2,Phones);
products(302,Sherlock Holmes);
relationships(302,1);
You need to JOIN the three tables.
SELECT p.*
FROM relationships r
INNER JOIN products p
ON p.prod_id = r.prod_id
INNER JOIN categories c
ON c.cat_d = r.cat_id
WHERE c.name = 'Books'
You have to join tables on related columns and specify WHERE clause to select all records where category name = 'Books'
SELECT p.*
FROM categories c
JOIN relationships r ON c.cat_id = r.cat_id
JOIN products p ON r.prod_id = p.prod_id
WHERE c.name = 'Books' -- or specify parameter like #Books
In SQL you often join related tables and beginners tend to join, whatever the situation. I would not recommend this. In your case you want to select products. If you only want to show products data, select from products only. You want to select products that are in the category 'Books' (or for which exists an entry in category 'Books'). Hence use an IN or EXISTS clause in order to find them:
select * from products
where prod_id in
(
select prod_id
from relationships
where cat_id = (select cat_id from categories where name = 'Books')
);
Thus you get a well structured query that tells the reader easily how the tables are related and what data you are actually interested in. Later, with different tables and data to select, this may keep you from duplicate result rows that you must get rid of by using DISTINCT or from getting wrong aggregates (sums, counts, etc.), because of mistakenly considering records multifold.
try this:
select p.Prod_id,p.name
from products p inner join relationships r on
p.prod_id = r.prod_id
where r.cat_id = (select cat_id from categories where name = 'books')
or
select p.Prod_id,p.name
from products p inner join relationships r on
p.prod_id = r.prod_id inner join categories c on c.cat_id = r.cat_id
where c.name = 'books'

How can i get book's title and author's firstname into the same result table when my database is designed like this

I have 3 tables
1. titles table have 2 fields(title,isbn)
2. authorisbn table have 2 fields(authorid,isbn)
3. authors table have 2 fields(authorid,firstname)
so i want to get a book's title(where the title is like '%Java%') and author's firstname of that book to fill in the same result table
what is the sql statement should i have to use to achieve that
my sql statement is like this
select titles.title, titles.isbn, authorisbn.authorid
from titles inner join authorisbn
where title like '%Java%' and authorisbn.isbn = titles.isbn
but it does not work because i can get only authorid
sorry for my english im learning it as well
I think this is your answer:
select v1.title, v1.isbn,authorisbn.authorid, authors.firstname
FROM books v1
INNER join authorisbn
ON v1.isbn = authorisbn.isbn
INNER JOIN books v2
on v2.isbn = authorisbn.isbn
INNER JOIN authors
WHERE v2.title like '%Java%';
Here, v1 and v2 are representing the books table, but when we use it multiple times in our query we should define them in new variables.
If this helps, please check it as an answer
try this.
select titles.title, titles.isbn, authorisbn.authorid, authors.firstname
from authorisbn
left join titles on titles.isbn = authorisbn.isbn
left join authors on authors.authorid = authorisbn.authorid
where titles.title like '%Java%'
you need to get to the authors table to get authors.firstname
select titles.title, titles.isbn, authorisbn.authorid, authors.firstname
from titles
inner join authorisbn
on authorisbn.isbn = titles.isbn
and title like '%Java%'
inner join authors
on authors.authorid = authorisbn .authorid
can move title like '%Java%' down into a where clause
where title like '%Java%'

mysql query with multiple left join in 3 tables?

i have a search query which will retrieve information from 3 tables i made the query so it retrieve the information from 2 tables and i don't know if i can combine the third one or not
SELECT *
FROM articles
INNER JOIN terms
ON articles.ArticleID = terms.RelatedID AND terms.TermType = 'article'
the third query is
SELECT * FROM categories where CategoryID in (something)
something is a filed in the articles tables which have value like '3,5,8'
i want do this 2 queries into 1 query and i don't know if it can be done by 1 query or not
without looking at your schema (which would be helpful) and some sample data try this query
SELECT *
FROM categories,articles
INNER JOIN terms
ON (articles.ArticleID = terms.RelatedID AND terms.TermType = 'article')
WHERE
FIND_IN_SET(categories.CategoryID,articles.categories)
here is the definition for FIND_IN_SET()
http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_find-in-set
If i understand you correctly. Looks like you have multiple categories for each article with the Category IDs all stored as a concatenated string.
SELECT A.*
FROM articles A
INNER JOIN terms T on A.ArticleID = T.RelatedID AND T.TermType = 'article'
LEFT JOIN categories C on C.CategoryID IN (3,5,8 OR A.CategoryIDs)
GROUP BY C.CategoryName
You want to LEFT JOIN since you may or may not have multiple categories, you can group by Categories to get disticnt category article pairs and CONCAT() to recombine article records as needed.