At the moment, we have 3 queries. In php, we loop over the first, then execute the 2nd multiple times, then which I'd like to have in one single query:
The first query is:
SELECT id FROM users
Then inside looping over those results, the 2nd is
SELECT id AS rid, count(recommendedById) FROM users WHERE id=$id
where $id is users.id from the first query.
The 3rd query is which is executed inside the 2nd loop is:
SELECT count(likes) AS likeCounter FROM posts WHERE author_id=$rid
and likeCounter is summed up to the first query.
Anyone able to bring this into one query?
Desired result
The result should be a row per user with a count of users he recommended and a sum of likes his recommended users got on their posts.
SELECT u.id,COUNT(DISTINCT ruid),sum(p.likes)
FROM users as u
LEFT JOIN (SELECT recommendedById as rid,id as ruid from users) as r ON r.rid = u.id
LEFT JOIN posts p ON p.author_id = ruid
GROUP BY u.id
You can do this:
SELECT u.id AS rid, count(recs.id), count(p.likes) AS likeCounter
FROM users u
LEFT JOIN posts p ON p.author_id=u.id
LEFT JOIN users recs ON recs.recommendedById=u.id
GROUP BY u.id
But a user has an id, and you use id from the users table. Isn't that always 1?
Related
I'm not too good with explaining things, apologies.
I have 3 tables that are similar to the below:
users
id
username
threads
id
title
user_id
lastpost_id
posts
id
content
thread_id
user_id
On a page listing forum threads, I want the username of both the thread author, and the last post author of that thread to be displayed, I'm attempting to achieve this in a single query.
My query looks like this:
SELECT t.*,u.username FROM threads t
INNER JOIN users u ON t.user_id=u.id
INNER JOIN posts p ON t.lastpost_id=p.id
ORDER BY t.id DESC
The first join enables me to get the username of the user id that started the thread.
The second join is what I'm not sure on, it can get me the user id but how do I get the username from that, as a 3rd join?
You can select the same table multiple times if you give it a different alias. You can give the fields aliases too:
SELECT
t.*,
tu.username as threadusername, /* Result field is called 'threadusername' */
p.*,
pu.username as lastpostusername
FROM threads t
INNER JOIN users tu ON t.user_id=tu.id /* thread user */
INNER JOIN posts p ON t.lastpost_id=p.id
INNER JOIN users pu ON p.user_id=pu.id /* post user */
ORDER BY t.id DESC
You can join to a joined table like this:
SELECT t.*,u.username,u2.username FROM threads t
INNER JOIN users u ON t.user_id=u.id
INNER JOIN posts p ON t.lastpost_id=p.id
INNER JOIN users u2 ON p.user_id=u2.id
ORDER BY t.id DESC
Note, I haven't had time to test it, but it should work (at least in MySQL).
I don't know if I got it correctly, but as per my understanding you can have a inner query to fetch the thread ids and then have a outer query to fetch the posts based on the thread id, have a max on post id and group by user id. Also join to user to have the name. Hope that helps.
I have a table for comments ("event_comments") to different events with the following columns:
post_id
event_id
username
comment
date
I want to be able to retrieve this info from the database and also be able to print the username, first name and last name; for this, I thought of using INNER JOIN, but it is not working for the following reason: I have 3 different profile types (3 different tables) "students", "guardians", "teachers" and when I try to use the INNER JOIN using "username" I get an error message saying that Column 'username' in from clause is ambiguous.
SELECT event_comments.post_id, event_comments.event_id, event_comments.username, event_comments.comment, event_comments.date,
students.first_name, students.last_name, students.picture,
guardians.first_name, guardians.last_name, guardians.picture,
teachers.first_name, teachers.last_name, teachers.picture
FROM event_comments
INNER JOIN students
INNER JOIN guardians
INNER JOIN teachers
USING (username)
ORDER BY date DESC
LIMIT 20
I tried to do this and it worked, but it only shows 1 comment per user; if the user has more than 1 comment then the info is ignored:
SELECT event_comments.post_id, event_comments.event_id, event_comments.username, event_comments.comment, event_comments.date,
students.first_name, students.last_name, students.picture,
guardians.first_name, guardians.last_name, guardians.picture,
teachers.first_name, teachers.last_name, teachers.picture
FROM event_comments
INNER JOIN students
INNER JOIN guardians
INNER JOIN teachers
GROUP BY username
ORDER BY date DESC
LIMIT 20
Does anybody how to get the INNER JOINs to work? is there a better way to do what I want? I hope I explained myself well.
Thanks!
do it like this:
SELECT event_comments.post_id, event_comments.event_id, event_comments.username, event_comments.comment, event_comments.date,
students.first_name, students.last_name, students.picture,
guardians.first_name, guardians.last_name, guardians.picture,
teachers.first_name, teachers.last_name, teachers.picture
FROM event_comments
INNER JOIN students
on event_comments.username=students.username
INNER JOIN guardians
on event_comments.username=guardians.username
INNER JOIN teachers
on event_comments.username=teachers.username
ORDER BY date DESC
LIMIT 20
This will work but assuming that a username from one table is not present in other tables, this will result into 0 rows.
a more logical approach would be to select each table then union it to join every result set like this :
SELECT e.post_id, e.event_id, e.username, e.comment, e_comments.date,
s.first_name, s.last_name, s.picture
from event_comments e
inner join students s
on e.username=g.username
UNION SELECT e.post_id, e.event_id, e.username, e.comment, e_comments.date,
g.first_name, g.last_name, g.picture
from event_comments e
inner join guardians g
on e.username=g.username
UNION SELECT e.post_id, e.event_id, e.username, e.comment, e_comments.date,
t.first_name, t.last_name, t.picture
from event_comments e
inner join teacher t
on e.username=t.username
EDIT:
To explain better about the query it just does this simple steps:
Query all comments from students using username to join post to students
Query all comments from guardians using username to join post to guardians
Query all comments from teachers using username to join post to teachers
Join results from students,guardians, teachers together
You need the using clause for each pair of joins:
FROM event_comments INNER JOIN
students
USING (username) INNER JOIN
guardians
USING (username) INNER JOIN
teachers
USING (username)
In MySQL, an inner join with no on clause is treated as a cross join. In other databases, an on or using clause is required for an inner join.
I have two tables: 'posts' and 'users' every post has a 'ref_id' column to get the user id who posted it.
Now, I am getting posts this way:
$this->db->query("SELECT * FROM posts WHERE time > '$timeLimit' LIMIT 50");
I can't understand how to join every result to get the poster related data as well. What I am doing right now is basically a loop inside a loop, where foreach of the result, get their user info. But it is pretty obvious that this is very wrong,
Apparently I need to start using joins, but how does one do it? this should be a really simple example to work with, I suppose.
Any help? Thank you.
SELECT posts.*, users.*
FROM posts
INNER JOIN users
ON posts.posted_by = users.id;
Like this:
SELECT
posts.*,,
users.Username
FROM posts
INNER JOIN users ON posts.ref_id = users.user_id;
Explanation:
To JOIN to any tables with each others, there are two things; the JOIN type and the join condition. There are three main types of join:
INNER JOIN, only the rows that match the join condition will be returned from the two tables no more rows. But:
LEFT OUTER JOIN, when you join two tables you will have one on the left of the join keyword and the other one will be in the right:
FROM Table1 <------------- This is the left table.
LEFT OUTER JOIN table2 .... <------------- This is the right table.
In LEFT OUTER JOIN the unmatched rows from the left table will be included in the result set.
RIGHT OUTER JOIN the unmatched rows from the right table will be included in the result set.
CROSS JOIN this will perform a Cartesian product from the two tables.
In our query, the query will reutrn all the users from the users table only if the ref_id equal to the user_id column form the posts table.
For more information and explanations:
A Visual Explanation of SQL Joins.
Another Visual Representation of SQL Joins.
Join syntax in MySQL
SELECT user.name
FROM users
INNER JOIN posts
ON posts.ref_id == user.id
AND posts.time > 50
http://www.w3schools.com/sql/sql_join_inner.asp
I need a little help setting up my query. I'm simply trying to access the amount of people who are in the same 'clan' by joining these two tables together, clan, users. Each users has a column 'clan' which is the same as the table clan's column 'roomOwner' and then I'm trying to get the table clan's information along with the amount of members so it would be like: room, roomOwner, members
So basically all I have is this:
SELECT c.*, count(u.clan) AS members FROM clans c inner join users u WHERE c.roomOwner = u.clan ORDER BY members;
It only shows one clan though. Any help please?
Your query has no GROUP BY clause. and I think it's only returning single record right? LEFT JOIN is needed here since there are possibilities that a clan has no member.
SELECT b.roomOwner, COUNT(a.clan) memberCount
FROM clan b
LEFT JOIN users a
ON a.clan = b.roomOwner
GROUP BY b.roomOwner
ORDER BY memberCount
You forgot GROUP BY. Do you have some "id" column in "clans" table? Group by that "id"
SELECT c.*, count(u.clan) AS members
FROM clans c
inner join users u ON c.roomOwner = u.clan
GROUP BY clans.id
And you need LEFT JOIN there instead of INNER JOIN if you want to see info about all clans, even having 0 users.
Perhaps this will help:
select c.*, count(links.id) as members
from clans c
left join users u on c.roomOwner = u,clan
group by u.clan
order by members
So, I understand how the relationships work in mysql but I'm having a hard time figuring out how its implemented in my code.
For example, say I have the 3 tables.
Table 1: users - user id, username, user city
Table 2: categories - category id, category name
Table 3: user_categories - user id, category id
If I were to query the database for every user that was in a particular city and list them out with the all of the categories they belong to... How would I do this? Would I need to loop through the results and do a separate query for each user, then list the results? Or, is there some magic query that will return a multidimensional array?
I believe the above would be many-to-many, correct me if I'm wrong....
EDIT In the user_categories table, a user can contain more than 1 category, I'm trying to figure out how to return all of them
Thanks!
You're absolutely right, it is a many-to-many query.
And from what I understand, what you're looking for is the ability to have some kind of hierarchical result to display, meaning for one user, have an array of all the categories he's assigned to...
Couple of things you could do:
Option 1: Query the users table:
SELECT u.user_id, u.username, u.user_city WHERE city = 'somecity';
From the results, get all the user_id's that match, put them in an array.
array(1,3,4,5)
Then execute a query by joining the 2 tables categories and user_categories, and passing the array as a comma separated list in a where in:
SELECT user_categories.user_id, categories.category_name
FROM user_categories INNER JOIN categories ON user_categories.category_id = categories.category_id
WHERE user_categories.user_id IN (1,3,4,5)
This will give you a list of user-id, category name that you can use in your script with the previous results to build your result set
option 2: my preferred, use MySQL's GROUP_CONCAT(http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html#function_group-concat).
SELECT users.user_id, users.user_name, GROUP_CONCAT(categories.category_name) AS categories
FROM users
INNER JOIN user_categories ON users.id = users_categories.user_id
INNER JOIN categories ON user_categories.category_id = category.id
WHERE user.user_city = 'somecity'
GROUP BY user.user_id
This will return something like:
user_id username categories
1 u1 cat1, cat2, cat3
2 u2 cat1, cat3
You can specify the separator by using SEPARATOR in group_concat.
You need to JOIN the tables.
If I were to query the database for every user that was in a particular city and list them out with the all of the categories they belong to
SELECT *
FROM users
INNER JOIN user_categories
ON (user_id)
INNER JOIN categories
ON (category_id)
WHERE ...
You could try:
SELECT u.user_id, u.username, u.user_city, c.category_id, c.category_name
FROM users u
INNER JOIN user_categories uc ON u.user_id = uc.user_id
INNER JOIN categories c ON uc.category_id = c.category_id
WHERE u.user_city = 'Cityname';
I haven't tested this, and there might be a more efficient way to do it, but it should work.
If you are unfamiliar with joins in mysql, check this out.