Joining on the same table more than once - mysql

I'm probably being a bit dumb, hopefully someone can help.
I have a simple 2 column user table (ID, USERNAME).
I have a comments table for images (COMMENT, COMMENTFROM, COMMENTTO)
COMMENTFROM is the ID of the user who made the comment. COMMENTTO is the ID of the owner of the image that the comment was added to. Both users are held within the USERS table.
I want to pull out and display rows like this
"really nice photo" - to USERXYZ - from USER123**
This has puzzled me, because if I join the USERS table to the comments table on:
WHERE comments.userfrom = users.id
That only gets me one (or the other) of the 2 usernames I need per row. Is there a way I can get both?
I'm not even sure how I would search for this answer on SOF, apologies if it has been answered before. If anyone can point me in the right direction it would be appreciated :)

You need to JOIN to the users table twice, and give them different identifiers (aka aliases) on each JOIN within your SQL.
SELECT
comment,
userFrom.username AS commentFrom,
userTo.username AS commentTo
FROM comments
JOIN users AS userFrom ON userFrom.ID = comment.commentFrom
JOIN users AS userTo ON userTo.ID = comment.commentTo

Please try following one
SELECT CONCAT(c.comment," - to ",
(SELECT USERNAME FROM user WHERE user.ID = c.COMMENTTO LIMIT 1),
" - from ",
(SELECT USERNAME FROM user WHERE user.ID = c.COMMENTFROM LIMIT 1)) FROM comments c

Related

Getting the number of posts that a user has posted?

How can I get the number of posts that a user has posted using one MySQL query?
I can't really think of anything but this, but there is no aggregate function on the join. So I'm not sure how to proceed. I am positive that joins will not accomplish what I need.
select a1.username as Username
from `logs` as a1
left join `logs` as a2
on a1.username = a2.username
For example, my logs table is filled with information about posts people have made. I want to find how many posts each user has made, i.e.
Username, Posts
User1 100
User2 200
etc
EDIT: Sorry for not providing enough information.
I have a table called logs and it has two columns. One column is called username and another column is called msg. It basically holds information about posts that people have posted.
For example, let's say someone named Red posts Hello world. It will be saved to the table logs and a new row will be created. username will be Red, and msg will be Hello world
I basically want to get the number of messages that EVERY SINGLE user has posted by their username. I.e. here is an example of what I want
Username Posts
Red 1
Blue 10
Sally 30
try this
SELECT Username, count(Posts)
FROM `logs`
GROUP BY Username;
Good luck.
I'm assuming that when you say you "can't use count(*) in a join", you mean that you tried and saw that it didn't work, rather than you can't use COUNT at all. So I'm using it here.
You're right that a JOIN is the wrong place for a COUNT. You want it up in the SELECT column list, and a GROUP BY down below. Aggregate by Username, and count the number of entries in each aggregate.
SELECT Username, COUNT(*) AS Count
FROM logs
GROUP BY Username
This query may help you, change this query as for your requirement
SELECT users.*, count( posts.user_id )
FROM posts LEFT JOIN users ON users.id=posts.user_id
GROUP BY posts.user_id
may be like
SELECT users.username, count( logs.username ) as posts
FROM users LEFT JOIN logs ON users.username=posts.username
GROUP BY users.username

Cross referencing tables in a mySQL query?

I have two tables. One is a table of users with a unique id field, and the other is a table of data, with a column that holds the user id of whoever generated that piece of data.
I want to do something like SELECT data,genned_by FROM datatable; but I want to replace the results for genned_by with SELECT username FROM users WHERE id = genned_by
So that the results from the query changes the userid into a username that corresponds with the other table.
I did some research and figured INNER JOIN might be what I'm looking for, but I'm left very unsure of how to use it after reading it. Help?
Try to use
SELECT d.data, u.username FROM database d INNER JOIN user u ON u.id=d.genned_by
Hope it helps you
SELECT datatable.data,users.username
FROM datatable, users
WHERE users.id = datatable.genned_by

Join on a cyclic relation (beginner)

I'm a beginner in queries and I'm struggling with one of them. Here are the two tables involved :
The askstobefriends table permit a user to add a friend in the application I m developping. The relational form of it is :
AskToBeFriends(ID (long), #UserAsker (long), #UserAsked (long), Accept (tinyInt))
So with this table we can see who asked to be friend and if it was accepted ...
The query I m trying to realize would permit to list all the user's friends from his ID and also return the friendship statut (accept field ==> waiting for an answer, accepted or refused).
Speretaly, it would be something like that :
SELECT Accept, UserAsker, UserAsked
FROM askstobefriends
WHERE UserAsker = '".$userID."' OR UserAsked = '".$userID."' ";
==> first issue : it can either be the user who asked to be friend with someone or the opposit, that why i've put and OR. After that, I d like that for everyfriend founded there's these informations :
SELECT colUserID, colUserLogin, colUserName, colUserFirstname
FROM userTable
WHERE colUserID == FRIEND
So I guess I need to do a join query, and in my join I have to be sure that I'm using the right foreign key from the asktobefriends tablefor each cases !! (once the key could be UserAsked and another time UserAsker depending on who asked to be friends :S )
Does anyone have a clue please :S ?? Thanks ;-) !!
Your design is wrong. A User asks to be friend of another User, so "Ask_to_be_friend" is the relation, and the cardinality is many to many, so the design will looks like this:
User_User_ID is UserAsker.
User_USer_ID1 is UserAskedtobefriend
and the query could be like (you'll get all the users that user_user_ID Asks to be friend of):
Select U.* from User as U
Join Ask_to_be_friend as A on
U.user_ID = A.User_user_ID
--where a.accept=1 if you add this, this will give
--you all the friends ID of the user_ID table User
If you want to get the names or extra info of the askedtobefriend you'll need a extra Join
Select U.* from User as U
Join Ask_to_be_friend as A on
U.user_ID = A.User_user_ID
Join User as U2 on
A.User_User_ID1=u2.User_ID
--where a.accept=1 ,with this you'll with get only the friends
You could join the tables using criteria that ensure only friends of :userID are returned. For example:
SELECT u.*, a.Accept
FROM askstobefriends a JOIN userTable u ON (:userID, u.colUserID) IN (
(a.UserAsker, a.UserAsked),
(a.UserAsked, a.UserAsker)
)

MYSQL : Problem in writing where clause according to scenario

I have a DB (user_interests) set up with 3 fields: i_id (unique), interest_id, uid.
Then a second DB (interests) set up with the interests: interest_id (unique), interest_name
I'd like to do an SQL query to return a list of interests that two users have in common: User A (owner of a profile) and user B (you/viewer of a profile). I guess I need to query user_interests, then JOIN interests to get the name of the interest.
SELECT user_interests.i_id, user_interests.uid, interests.interest_name
FROM databases.user_interests
LEFT JOIN databases.interests
ON interest.interest_id = user_interest.interest_id
WHERE _______________
I'm confused about the where clause (if that is the correct way to do it at all). My goal is to get the interest_id from user_interests.interests where user_interests.uid is both A and then B (in separate rows).
I saw this link, but couldn't figure out what exactly I was missing: Group by x where y = A and B and C
I would solve it by joining two copies of user_interests, one which is filtered for user A (the profile owner), and one for user B, (the profile viewer).
SELECT *
FROM interests I
INNER JOIN user_interests A ON
A.interest_id = I.interest_id
AND A.user_id = {profile owner}
INNER JOIN user_interests B ON
B.interest_id = I.interest_id
AND B.user_id = {profile viewer}
Alternatively, more along the lines of the snippet you provided, you could complete the where clause with something like...
SELECT * FROM interests
WHERE interest_id in (SELECT interest_id
FROM users
WHERE user_id = A)
AND
interest_id in (SELECT interest_id
FROM user_interests
WHERE user_id = B)
Hope one of those works for you! Let me know if I can clarify
I don't think you need the where clause in this case just remove it and you will get the set of data you are looking for:
SELECT user_interests.i_id, user_interests.uid, interests.interest_name
FROM databases.user_interests
LEFT JOIN databases.interests
ON interest.interest_id = user_interest.interest_id
You may also create a where statement such as the following if you are looking to get a specific result set. I'm not discrediting the answer previously submitted, I am simply trying to help you with the specific WHERE statement you're looking for.
SELECT user_interests.i_id, user_interests.uid, interests.interest_name
FROM databases.user_interests
LEFT JOIN databases.interests
ON interests.interest_id = user_interests.interest_id
WHERE user_interests.uid IN ('A','B');
Please also note, that I changed your ON join to use interests and user_interests, with 's' appended to both, as those are the names of the table. They maintain the same schema name as they are assigned in the database.
Your query is correct remove the where part and run it. It will give you the same output as you need...

Help building a sql query that uses inner join

I am trying to build a sql query that I think it involves inner joins, but I can't figure it out. Here's the model:
There's two tables: comments, posts
Among many columns, there's the following important ones: comments.id, comments.user_id (owner), comments.post_id (reference to posts table), posts.id, posts.editor_id (which is the person, ie, owner of post).
I want to get the comments that either
1) current user has written, so something like:
select * from comments where user_id = <<current_user_id>>
2) (Assume current_user is editor). Get all comments that belong to a post that you have created.
This is what I have, but I get multiple lines....what am I missing?
select * FROM comments INNER JOIN posts ON comments.post_id = <<test_id>>
WHERE posts.editor_id = <<current_user.editor_id>>;
If you could give me a sql query that includes both of these things, that would be amazing.
Thanks!
Im not sure what you mean by "multiple lines" as you would return a row for each comment.
This should do it.
SELECT comments.*
FROM comments
INNER JOIN posts
ON comments.post_id = posts.id
WHERE posts.editor_id = #editorID;
I want to get the comments that either 1) current user has written, so something like: select * from comments where user_id = <>
That's correct. What's wrong with that?
Get all comments that belong to a post that you have created. This is what I have, but I get multiple lines
Well... you're supposed to. Looking at the schema it's indeed a post could contain many comments. The query given by tyrongower should do what you want.
Going with your requirements, this should work for you:
SELECT * FROM comments
WHERE (user_id = 1)
OR (post_id IN (SELECT id FROM post WHERE editor_id = 1))
In the above query "1" is used as a sample and should be replace with the id of current user.