Select items where ID present in another column MySQL - php

I have a table of albums, each album has an ID.
I also have a table of reviews, each review is linked to a corresponding album through the column albumID.
I'm wondering how I can select all albums who's ID's are present in the reviews table.
I was thinking of selecting all albumId's from the reviews column then doing a select where id in but I feel like this would be horribly inefficient.
This is in MySQL
Albums Table
- ID
Reviews Table
- ID
- albumID
Desired result: All albums who have a review. (eg: All albums that have their ID present in the Reviews table)

Here's one approach using a simple JOIN. The inner join notation will only include records that exist in both tables. It allows you to access data in both tables which may be useful if you need data out of reviews too.
Select * from albums A
inner join reviews R
on A.ID = R.AlbumID
This next approach is generally the fastest but you can only get data from albums. This uses what's known as a correlated sub query and is generally the fastest approach.
SELECT * from albums A
where exists (Select 1 from reviews R where A.ID = R.albumID)
and a third approach but generally the slowest... uses a concept called IN(). The sub query here generates a list of ID's from reviews and only shows albums in that list.
Select * from albums where ID IN (SELECT albumID from Reviews)

This would work:
select a.* from albums as a
inner join reviews as r
on r.albumID = a.ID

Related

How do you fetch records from a table with order of another table using foreign key

I have two tables in my SQL, 'post' and 'business'
The columns in the post are:
Post_ID
Content
Img
Business_ID
The columns in business are
Business_ID
Business name
Business rating
What I want is I want the posts which are posted by businesses with high business rating come first before others, please is there a way to fetch the posts with order of business rating???
To order results of posts with associated business rating you need a join query
select p.*
from posts as p
join business as b on b.business_id = p.business_id
order by b.business_rating desc
To arrange the ratting use order by query
select * from posts,business order by business_rating where posts.business_ID=business.business_ID;

Query result from database

I have two tables : galleries and shared galleries.
Structure of galleries: (for storing images of individual students. One student contains multiple images)
id, student_id, classroom_id, image
Structure of shared_galleries: (for storing images which are common to all students in a classroom. One classroom contains many images):
id,classroom_id,image
Other than these two tables I have students table and classrooms table. Students table store the classroom_id.
I need to get a query so that I can display the images stored in 'galleries' for a student and those stored in shared gallery of the classroom in which that student belongs in a single page. How can I achieve this ? Something like this returns duplicated results :
select galleries.id as gid,
shared_galleries.id as sid,
galleries.student_id, galleries.classroom_id
from galleries
inner join shared_galleries on galleries.classroom_id=shared_galleries.classroom_id
where galleries.student_id=31 and galleries.classroom_id=28
You will need to join the student to the shared_galleries along the relations to get the right results
SELECT
g.image AS image,
0 AS is_shared
WHERE
g.student_id = :student_id
FROM
galleries AS g
UNION
SELECT
sg.image AS image,
1 AS is_shared
FROM
shared_galleries AS sg
LEFT JOIN classrooms AS c ON c.id = sg.classroom_id
LEFT JOIN students AS s ON s.classroom_id = c.id
WHERE
s.id = :student_id
This should give you all the images for a student with :student_id,
I've also added the is_shared column in case you need to know the origin of the image
Since your images are stored on a per-record basis (in both galleries and shared galleries, using a JOIN is not needed. Use a UNION instead:
SELECT
galleries.id AS ID,
galleries.student_ID AS StudentID,
galleries.classroom_id as ClassroomID,
galleries.image as Image
WHERE
galleries.student_id = 31
UNION
SELECT
shared_galleries.id AS ID,
NULL AS StudentID,
shared_galleries.classroom_id as ClassroomID,
shared_galleries.image as Image
WHERE
shared_galleries.classroom_ID = 31
This will produce a list of records, with each record containing one image (since the number of images per student and the number if images per classroom is never consistent)
If you want do a little extra and ensure that your classroom images are always linked to the correct student, then declare a variable at the beginning to set the student_id value, and then use it in the second SELECT statement.

SQL - Return books that user owns

I'm doing I'm having a bit of a problem performing a query in my university project. I got a website where users share the books that they've read and I have a page where the user can view the books he has added (the books he owns).
For that I believe I need the logged user's id, which I store in a session PHP variable, the user id is in table users.
The information about the books is stored in a table books and it has its own id primary key.
Then, to show who owns what I have a table owns_book (id, u_id, book_id).
Right now for testing I've got 26 books total, 25 of them are added by a user with id of 57 and 1 book by user with id of 49.
When I run this query:
SELECT id, title, author, category, cover, added, user_id FROM books, users
WHERE user_id=49 AND id IN(SELECT book_id FROM owns_book)
AND user_id IN(SELECT u_id FROM owns_book)
And the result is a mess, I don't get the expected one book, I also get books added by the other user.
Can someone please show me the correct query that I need or if I need to change the structure of my tables? Thanks.
EDIT:
users(user_id, ...)
books(id, title, author, publisher, published, cover... )
owns_book(id, u_id, book_id)
It looks like you're looking to to grab everything from your books table that is owned by a specific customer. If that's the case, you can try
SELECT * FROM books
JOIN owns_book
ON books.id = owns_books.book_id
WHERE owns_book.user_id = 49
This will select all of the props from your books table then joins the tables based on on the ID of the book being equal to the book_id of the owns_book. Lastly, add the parameter - you only want to see user_id = 49.
You can simplify this query and use a LEFT JOIN...
SELECT books.id, title, author, category, cover, added, users.user_id
FROM users
LEFT JOIN owns_book on owns_book.user_id = users.user_id
LEFT JOIN books on books.id = owns_book.id
WHERE users.user_id=49
This links the user_id and lists any books owned by this user_id ( the ON bit of the JOIN). The WHERE clause just limits to listing records for the user_id your after.
If in the main list of columns, there is a column on multiple tables ( like user_id) then prefix it with the table name to allow the database to detect which column you want to use (even though they may be the same value).
You could also use inner join to join the tables users and books with the owns_book table:
SELECT id, title, author, category, cover, added, user_id
FROM owns_book
INNER JOIN users ON users.id = owns_book.u_id
INNER JOIN books ON books.id = owns_book.book_id
WHERE users.user_id=49

How do I SELECT and COUNT from two diferent tables to get the "like count" of a post in one query?

I'm kind of noobie to this, but I'm trying to learn, I have two tables, the first one (NEWS) has all the information about posts of a blog, it has the follow structure:
* NEWS (TABLE 1)
- id_new
- id_category
- date
- ...etc
- **likes**
and I have a second table:
* LIKES (TABLE 2)
- id_like
- id_new
- id_user
- date
- ip_user
So, I want to select all the rows from TABLE 1 to display all the news but also i want to count the likes and get the COUNT of each new as like column.
This approach left joins the NEWS table to a subquery which finds the number of likes for each news story.
SELECT
t1.*,
COALESCE(t2.likes, 0) AS likes
FROM NEWS t1
LEFT JOIN
(
SELECT id_new, COUNT(*) AS likes
FROM LIKES
GROUP BY id_new
) t2
ON t1.id_new = t2.id_new
Note that here a story having no likes would not appear at all in the LIKES table and would receive a count of zero. Also note that I assume that every record in the LIKES table corresponds to a logical like. If not, then the query could be modified to count something else.
You can do it like this
SELECT table1.*, table2.*, count(table2.id_like) as like FROM news AS table1
INNER JOIN likes AS table 2 ON table1.id_new = table2.id_new;
OR
SELECT table1.*, table2.*, count(table2.id_like) as like FROM news AS table1
LEFT JOIN likes AS table 2 ON table1.id_new = table2.id_new;
you can use prepared statement
for example
$stmt = $pdo->prepare("SELECT count(*) FROM TABLE_1);
$stmt2 = $pdo->prepare("SELECT count(*) FROM TABLE_2);
//then execute
just read more on prepared statement
Try this
SELECT n, (SELECT count(*) FROM like l WHERE l.id_new = n.id_new) FROM news n
Use something like :
SELECT *, (SELECT COUNT(*) FROM LIKES WHERE LIKES.id_new =id_new) AS newsLikesCount FROM NEWS ORDER BY date;
This query would return all news and their number of likes
select n1.* , numberOfLikes.number_of_likes
from news n1
left join
(select n.id_news, count(l.id_like) as number_of_likes
from news n
left join likes l on n.id_news = l.id_new
group by n.id_news) numberOfLikes on n1.id_news = numberOfLikes.id_news
The important concepts here is understanding how two tables are joined together (1), how group by works(2), and how to aggregate l.id_likes using count(3).
(1). Left join preserves everything in the NEWS table and join them
with news link to the news.
(2). Then we group the rows base on id_news from the news. However,
mysql gets confused because it doesn't know what to do with id_like
from the likes table that we included in our select clause. Don't
worry my friend, This is where count comes in.
(3). We count the number of id_likes base for each id_news since we
are grouping the rows base on id_news.
I hope this helps. and welcome to StackOverfow. If you find this answer of any other answer helpful please mark it as the solution. That way it will help the community and fellow programmers in the future if they run into the same problem as you. Cheers.
Edit: to include all columns from news table we simply join the result from above back to the news table itself. and we select everything from the news table n1 and only number_of_likes from the result we created above.

How to use join for more than two table?

I have three tables.They are
tb_albums---->id,title, description
tb_photos---->id,album_id, photo
tb_tags---->id,album_id, tag
Here i want to get the albums details and it photos & it tags through tb_albums.id.
How to use join query here?
Normally, you can use as many tables in JOIN, as you'd like. Just add another JOIN statement. You can refer to k102's answer for the correct syntax (which doesn't produce correct result though).
But in this particular case you don't want to use simple JOIN on all tables, unless you have only one photo per album and only one tag per album. If you have more than one photo per and more than one tag per album, JOIN both tables on album_id in single query will produce Cartesian product of both, in other words all possible combinations of tags and photos from each albums. For N photos and M tags that's N * M results, instead of N + M.
Also, there is no point of joining with tb_albums, as you do not need to repeat information about each album for each photo and each tag.
Proper approach would be to have 3 separate simple SELECTs from each table and combining their result on application level.
If for some awkward reason you'd need to do that with one query, you can do something like:
SELECT * FROM tb_albums as A JOIN
(SELECT 'photo', id, photo as value FROM tb_photos
UNION ALL
SELECT 'tag', id, tag as value FROM tb_tags) as B ON B.album_id = A.id
Note, this is way less optimal than separate SELECTs, you should only do this if you have no other choice.
select * from tb_albums a
join tb_photos p on a.id = p.album_id
join tb_tags t on a.id = t.album_id

Categories