SQL multiple join tidy up - mysql

I have this statement:
SELECT board.*,numlikes
FROM board
LEFT JOIN (
SELECT pins.board_id, COUNT(source_user_id) AS numlikes
FROM likes
INNER JOIN pins ON pins.id = likes.pin_id
GROUP BY pins.board_id
) likes ON board.id = likes.board_id
WHERE who_can_tag=''
ORDER BY numlikes DESC
LIMIT 10
I can then extract rows from board using ".$info['board_name'].".
However, I'm not good with multiple joins and I need to join another table to this besides the board and likes tables.
The third table is user and matches to board.user_id with user.user_id.
how can I then use this data to extract a username from user?
Wouldn't ".$info['username']." search for the field username in the table board still?

This will do what you want:
SELECT board.*,
`user`.username,
numlikes
FROM board
INNER JOIN `user` ON board.user_id = `user`.user_id
LEFT JOIN (
SELECT pins.board_id, COUNT(source_user_id) AS numlikes
FROM likes
INNER JOIN pins ON pins.id = likes.pin_id
GROUP BY pins.board_id
) likes ON board.id = likes.board_id
WHERE who_can_tag=''
ORDER BY numlikes DESC
LIMIT 10

Related

Error in my MYSQL query?

Trying some queries on the database, but I have a problem. Can somebody help me with proper query?
This is what I need
SELECT
IdNews, Caption, NewsText, NumberOfViews, NumberOfComments,
PublishDate, CoinValue, category.IdNewsCategory,
NewsCategory, country.IdCountry, CountryName, news.IdUser,
FirstName, LastName, Picture, DateTimeUpCoin
FROM
news
INNER JOIN
category ON category.IdNewsCategory = news.IdNewsCategory
INNER JOIN
country ON news.IdCountry = country.IdCountry
INNER JOIN
user ON user.IdUser = news.IdUser
WHERE
news.IdCountry = 1
LIMIT 0, 10
ORDER BY
NumberOfViews DESC
You have written wrong query for Order by.
In query, LIMIT comes always last.
You need to write corrected query as per below :
SELECT
IdNews,Caption,NewsText,NumberOfViews,NumberOfComments,
PublishDate,CoinValue,category.IdNewsCategory,
NewsCategory,country.IdCountry,CountryName,news.IdUser,
FirstName, LastName,Picture, DateTimeUpCoin
FROM news
INNER JOIN category ON category.IdNewsCategory = news.IdNewsCategory
INNER JOIN country ON news.IdCountry = country.IdCountry
INNER JOIN user ON user.IdUser = news.IdUser
WHERE news.IdCountry = 1
ORDER BY NumberOfViews DESC
LIMIT 0, 10
IdCountry column is present in both the tables news and country. That's why it is showing error. Prepend table name before IdCountry in where clause. Put ORDER BY before LIMIT.
SELECT IdNews,Caption,NewsText,NumberOfViews,NumberOfComments,PublishDate,CoinValue,category.IdNewsCategory, NewsCategory,country.IdCountry,CountryName,news.IdUser,FirstName, LastName,Picture, DateTimeUpCoin
FROM news
INNER JOIN category ON category.IdNewsCategory = news.IdNewsCategory
INNER JOIN country ON news.IdCountry = country.IdCountry
INNER JOIN user ON user.IdUser = news.IdUser
WHERE news.IdCountry =1
ORDER BY NumberOfViews DESC
LIMIT 0 , 10

Select Query based on values in result set

Is there anyway to select all from 1 table based on the result of one query which contains multiple values without having to do 2 separate queries?
Say long join query will produce a list of id's
SELECT xyz FROM table long join query WHERE id = array of ids found in result table
added example:
SELECT * FROM tweets as t
where t.user_id
in(
SELECT uff.id, uff.username
FROM users as uf
LEFT JOIN followlinks as fl
ON uf.id = fl.user_id
LEFT JOIN users as uff
ON fl.follow_id = uff.id
WHERE uff.id = 1
)
The bit in the parenthesis returns an id and user name of who the user is following (uff.id=1)
How do i then get all 'tweets' by all the id's in the generated resultset
You can use subquery:
SELECT * FROM `table1` WHERE `id` IN (SELECT `table2`.id FROM `table2` )
You might want to check documentation for syntax
SELECT xyz FROM table_A join table_B WHERE table_A.id IN (SELECT ID FROM table_C);
I think you mean something like
edited after the OP edit
SELECT * FROM tweets as t
WHERE t.user_id
in(
SELECT uff.id //remove the second field, you just need the id
FROM users as uf
LEFT JOIN followlinks as fl
ON uf.id = fl.user_id
LEFT JOIN users as uff
ON fl.follow_id = uff.id
WHERE uff.id = 1
)
After trying the in clause I coudnt get the results I was after but after rethinking what I was trying to do I got my results with an additional join clause
SELECT uff.username, t.content
FROM users as uf
JOIN followlinks as fl
ON uf.id = fl.user_id
JOIN users as uff
ON fl.follow_id = uff.id
JOIN tweets as t
ON t.user_id = uff.id
WHERE uf.id = 1

MySQL query and count from other table

I would like to get the data from one table, and count all results from other table, depending on the first table data, here is what I tried:
SELECT
cars.*, (
SELECT
COUNT(*)
FROM
uploads
WHERE
uploads.cid = cars.customer
) AS `count`,
FROM
`cars`
WHERE
customer = 11;
I dont really have an idea why its not working, as I'm not a regular MySQL user/coder...
Could anyone direct me in the right direction with this one?
SELECT
c.*, COUNT(u.cid) AS count
FROM
cars c
LEFT JOIN
uploads u
ON
u.cid=c.customer
WHERE
u.customer = 11;
GROUP BY c.cid
Try it by joining both tables using LEFT JOIN
SELECT a.customer, COUNT(b.cid) totalCount
FROM cars a
LEFT JOIN uploads b
ON a.customer = b.cid
WHERE a.customer = 11
GROUP BY a.customer
using COUNT(*) in LEFT JOIN will have records to have a minimum count of 1.
SELECT cars.*,COUNT(uploads.*) as uplloaded
from cars
left outer join uploads on uploads.cid = cars.customer
where cars.customer = 11
group by uploads.cid;
Try this :
SELECT customer, COUNT(cid) totalCount
FROM cars
INNER JOIN uploads
ON (customer = cid)
WHERE customer = 11
GROUP BY customer

SELECT count(*) on Intermediary Table with Many-Many relationship Only if Exists in Both Related Tables

I have 3 tables: users, courses and courseusers. Courseusers is the intermediary table that joins courses.idCourse with users.idUser. However, the intermediary table has no foreign key constrains and ON DELETE CASCADE or ON UPDATE CASCADE.
Users:
idUser|name
Courses:
idCourse|name
Courseusers:
id|idUser|idCourse
My question is, how do I get the top 3 most subscribed courses (most entries in courseuser), while ignoring manually deleted users from the users and courses tables (they will still exists as entries in courseuser).
What I have right now:
SELECT c.idCourse, c.name, count(*) as count
FROM courseusers as cu
JOIN course as c
ON cu.idCourse=c.idCourse
JOIN users as usr
ON (usr.idUser=u.idUser)
GROUP BY u.idCourse
ORDER BY count DESC
LIMIT 3
Try to use the following query
SELECT c.idCourse, c.name, count(*) as count
FROM courseusers as cu
LEFT JOIN course as c
ON cu.idCourse=c.idCourse
LEFT JOIN users as usr
ON (usr.idUser=u.idUser)
GROUP BY u.idCourse
ORDER BY count DESC
LIMIT 3
http://sqlfiddle.com/#!2/0567a/1
SELECT
c.name,
COUNT(1) AS total
FROM Courceusers cu
JOIN Cources c USING(idCource)
JOIN Users u USING(idUser)
GROUP BY 1
ORDER BY 2 DESC
LIMIT 3;
Join all tables based on table Users not on the intermediary table
SELECT a.idUser, a.Name, COUNT(c.idCourse) totalCount
FROM Users a
INNER JOIN CourseUsers b
ON a.idUser = b.idUser
INNER JOIN Courses c
ON b.idCourse = c.idCourse
GROUP BY a.idUser, a.Name
ORDER BY totalCount DESC
LIMIT 3
select
CourseUsers.idCourse,
Courses.name,
COUNT(distinct CourseUsers.idUser) as Subscribers
from CourseUsers
inner join Courses on CourseUsers.idCourse = Courses.idCourse
inner join Users on CourseUsers.idUser = Users.idUser
group by CourseUsers.idCourse, Courses.name
order by Subscribers desc
limit 3

MYSQL select statement - 5 results from each user

I'm trying to do a select statement and it works except that it's not limiting the number of results for each user (U.id) to 5.
SELECT F.id,F.created,U.username,U.fullname,U.id,I.id,I.cached_image
FROM favorites AS F
INNER JOIN users AS U
ON F.faver_profile_id = U.id
INNER JOIN items AS I
ON F.notice_id = I.id
WHERE faver_profile_id IN ('.$users.')
GROUP BY I.id HAVING COUNT(U.id) <= 5
ORDER BY F.faver_profile_id, F.created DESC
I'm grouping by I.id to eliminate duplicates. From my research it looks like you can only use HAVING COUNT if your also grouping by that column, but I cannot group by U.id or I'd lose results rows.
Instead of HAVING, can you slap a LIMIT 5 in there?
Edit: OP cannot LIMIT entire query,
and, AFAIK, MySQL does not support LIMIT in subqueries,
so you can create a temporary table with your five (5) user ids:
create table temp_table ( id INT );
insert into temp_table (id) SELECT U.id FROM users U LIMIT 5;
SELECT F.id,F.created,U.username,U.fullname,U.id,I.id,I.cached_image
FROM favorites AS F
INNER JOIN temp_table AS Ut
ON F.faver_profile_id = Ut.id
INNER JOIN items AS I
ON F.notice_id = I.id
WHERE faver_profile_id IN ('.$users.')
GROUP BY I.id
ORDER BY F.faver_profile_id, F.created DESC;
drop table temp_Table;
Let us know how that works.