mysql join 2 tables with on condition , keep some values - mysql

I have 2 tables.
users(id,username) and links(id,usernameORid).
Example of rows: users{ [1,test] , [2,stack] } and links{ [1,overflow] , [2, 1] }
So, table links may contain username or id from table users. As you can see in the example,
usernameORid from links may not contain the id or username from users.
I hope you understood my example.
Now, i have this query:
SELECT l.usernameORid, u.username, u.id
FROM links l
LEFT JOIN users u
ON l.usernameORid= u.id
LEFT JOIN user_roles ur
ON ur.userID = u.id
WHERE ur.roleID < 4
group by u.id
But this query does not return rows from links if usernameORid is not an actual username or id from users.
In the previous example, will not return row [1,overflow]. I want that row too.
How can i achieve that?
EDIT: The problem is partialy related to
LEFT JOIN user_roles ur
ON ur.userID = u.id
WHERE ur.roleID < 4
but still, how can i achieve that?
user_roles ( id,userID,roleID)

Change your final WHERE condition to:
WHERE ur.roleID < 4 OR u.id IS NULL
This will allow it to return rows that didn't have a match in users. Normally a LEFT JOIN does that by itself, but since you're doing an additional join on that table, the WHERE clause is filtering those non-matching rows out because they don't have a roleID.

You can use an OR statement in your join between links and users. This will allow you to pick up users records where the link.usernameORid is equal to either the users.id or the users.username
SELECT l.usernameORid,
u.username,
u.id
FROM links l
LEFT JOIN users u ON
l.usernameORid = u.id OR
lusernameORid = u.username
LEFT JOIN user_roles ur
ON ur.userID = u.id
WHERE ur.roleID < 4
GROUP BY u.id
This will still cause records to drop if the found users->user_roles.roleID is less than 4. If you wanted to have link records maintained regardless of whether of a user was found by username or ID then you would need to subquery the users and user_roles table joins and apply your WHERE statement there instead. This query is below:
SELECT
l.usernameORid,
u.username,
u.id
FROM links l
LEFT JOIN
(
SELECT
users.username,
users.idusers
FROM
users
LEFT JOIN user_roles ON
user_roles.userID = users.id
WHERE
user_roles.roleID < 4
) u ON
l.usernameORid= u.id OR
l.usernameORid = u.username
group by u.id
Furthermore, if you wish the 2nd or 3rd column of your return to hold the value that is in l.usernameORid when the users table lacks a match... if your users.id is always numeric you could do some trickery with a CASE statement:
SELECT
l.usernameORid,
Coalesce(u.username, CASE WHEN .lusernameORid REGEXP '^[0-9]+$' THEN NULL ELSE l.usernameORid END) as username,
Coalesce(u.username, CASE WHEN .lusernameORid REGEXP '^[0-9]+$' THEN l.usernameORid ELSE NULL END) as userid
FROM links l
LEFT JOIN
(
SELECT
users.username,
users.idusers
FROM
users
LEFT JOIN user_roles ON
user_roles.userID = users.id
WHERE
user_roles.roleID < 4
) u ON
l.usernameORid= u.id OR
l.usernameORid = u.username
group by u.id
Keep in mind though, that if the users table doesn't have a match for the links.usernameORid then only the username OR the id could be determined, so you will have a NULL in one of the two fields.

Related

SQL - how to remove whole row if one of the column in subquery return NULL

I am stuck in 1 SQL query
SELECT u.*,
um2.meta_value as parent_user_id,
( select u.user_email FROM wp_users u WHERE u.ID = um2.meta_value ) AS parent_user_email
FROM
wp_users u
JOIN wp_usermeta um2 ON u.ID = um2.user_id
AND um2.meta_key = 'parent_user_id'
GROUP BY
u.ID
This query return 4 row ( As shown in the screenshot )
I want a scenario like : If subquery return NULL , then the whole row will not be shown.
So in this example "childthree" should not be shown , as "parent_user_email" is NULL , so the whole 3rd row need to remove
Use a join instead:
SELECT u.*, um2.meta_value as parent_user_id,
u2.user_email as parent_user_email
FROM wp_users u JOIN
wp_usermeta um2
ON u.ID = um2.user_id AND
um2.meta_key = 'parent_user_id' JOIN
wp_users u2
ON u2.ID = um2.meta_value
GROUP BY u.ID;
Note: This assumes that the email value itself is never NULL. If that is possible, add WHERE u2.user_email IS NOT NULL.
Also, your query should fail because the GROUP BY columns are inconsistent with the SELECT. However, logically it seems ok, because there is only one parent and user email per user. However, I would include those columns in the GROUP BY.

Get data even if one row is NULL

I have this query to get users from the users table and also get the latest time (a timestamp) from the logs table where the entry is "login_ok". This is intended to show a list of users and the last time them logged in.
SELECT u.`id`, u.`email`, u.`firstname`, u.`lastname`, u.`type`, u.`creation_date`, MAX(l.`time`) as `last_login`
FROM `users` AS u
JOIN `logs` AS l ON u.id = l.user_id
WHERE l.`action` = 'login_ok'
AND `visible` = 1
GROUP BY u.`id`
ORDER BY u.`id` ASC
My issue here is: if the user has never logged in, the "login_ok" entry doesn't exists for that user, so the query cannot get that user data.
Is there any way to get all user data even if the l.time on logs doesn't exist? I tried with JOINname_admin_users_logAS l ON (l.timeIS NOT NULL AND u.id = l.user_id) but still not showing that new user without login log.
Use a LEFT JOIN instead of a regular JOIN (which actually means INNER JOIN), and move the filter on action = 'login_ok' to that LEFT JOIN clause.
NB : from your query we cannot tell from which table the visible column comes from, so I assumed it is related to users...
SELECT
u.id,
u.email,
u.firstname,
u.lastname,
u.type,
u.creation_date,
MAX(l.time) as last_login
FROM users AS u
LEFT JOIN logs AS l
ON u.id = l.user_id and l.action = 'login_ok'
WHERE u.visible = 1
GROUP BY u.id
ORDER BY u.id ASC
Use a left join:
SELECT u.`id`, u.`email`, u.`firstname`, u.`lastname`, u.`type`, u.`creation_date`, MAX(l.`time`) as `last_login`
FROM `users` u LEFT JOIN
`logs` l
ON u.id = l.user_id AND l.`action` = 'login_ok'
WHERE u.`visible` = 1
GROUP BY u.`id`
ORDER BY u.`id` ASC;
This assumes that visible is in users. If it is in logs, then that condition should also be in the ON clause.
You can simply ignore the login_ok and search for all values of l.action.
But if you want only values with login_ok and null then you can do:
WHERE l.`action` = 'login_ok' OR l.`action` is null
You should use LEFT/RIGHT joins instead of JOIN(inner)
For example:
SELECT u.id, u.name, l.time
FROM users u LEFT JOIN logs l
ON u.id=l.user_id
In this case you'll get ALL the records from 'users'(the table on the left in the select: users - left, logs - right) and all records from the right('logs') table for which condition u.id=l.user_id is true.
Finally you'll get something like this:
u.id u.name l.time
1 John 10.00am
2 Mary 2.15pm
3 Mark null

MySQL not null in left join condition

My query looks like:
SELECT *
FROM users U
LEFT JOIN posts P ON P.userId = U.id AND P.userId IS NOT NULL;
Why the query also return result where userId is null ?
I know that for my needs I can use INNER JOIN to get only posts related to user but is so strange that LEFT JOIN support multiple conditions, but not work with NOT NULL conditions.
This is because "posts" does not contain the null-values and hence they can´t be filtered at that stage. The Null-values are only generated trough the join, when the server can´t find a corresponding row on the right table. So just put the not null in the where clause and it will work:
SELECT * FROM users U LEFT JOIN posts P ON P.userId = U.id WHERE userId IS NOT NULL;
(EDIT: You should use an inner join for productive work though, as it is the proper way and will give you much greater performance.)
You can also see all users who don´t have posts by inverting that:
SELECT * FROM users U LEFT JOIN posts P ON P.userId = U.id WHERE userId IS NULL;
You are outer joining the posts table. This means for every users record that has no match in posts you still get this record with all posts columns null.
So say you have a users record with userid = 5 and there is no posts record with id = 5.
ON P.userId = U.id AND P.userId IS NOT NULL
The two combined conditions are not met (there is no record with userid 5), so you get the users record with all posts columns set to null in your results.
Maybe you are simply looking for an inner join? All users records with their posts data?
This query:
SELECT *
FROM users U LEFT JOIN
posts P
ON P.userId = U.id AND P.userId IS NOT NULL;
Returns all rows in the users as well as all columns from posts, regardless of whether or not they match. This is true, regardless of whether the ON clause evaluates to TRUE or FALSE.
What you want is a WHERE. In addition, you should only select the columns from users:
SELECT u.*
FROM users U LEFT JOIN
posts P
ON P.userId = U.id
WHERE P.userId IS NOT NULL;
Note that you can also accomplish this using NOT IN or NOT EXISTS.
Because the LEFT JOIN must return every row from the left table by it's definition. The raw may be augmented with the data of the right table depending on the ON clause evaluation. So the following code must return a row.
select u.*, p.*
from (
select 1 as id
) u
left join (
-- no data at all
select 2 as id where 1=2
) p on 3 = 4 -- never is true
Try this
SELECT * FROM users U LEFT JOIN posts P ON P.userId = U.id
SELECT * FROM users U LEFT JOIN posts P ON P.userId = U.id where P.userId IS NOT NULL;
IS NOT NULL WITH JOINS
SELECT * FROM users
LEFT JOIN posts ON post.user_id = users.id
WHERE user_id IS NOT NULL;

SQL LEFT JOIN WHERE

I have two tables, one with settingIDs and values of those settings for each userID and another with userIDs, their emails and user names.
I am trying to join the values of specific settings, the problem is that not all users have this specific setting tied to their ID, so I end up with less rows than I actually need.
Table 1
userID settingID settingValue
Table 2
userID userDOB userEmail userName
My query looks like this:
SELECT u.userID, u.userEmail, s.settingValue
FROM users u
LEFT JOIN userSettings s ON u.userID = s.userID
WHERE s.settingID = 1
What do I need to do to get all of the users in the list?
Your where clause turns you left join into an inner join. Put the condition in the JOIN
SELECT u.userID, u.userEmail, s.settingValue
FROM users u
LEFT JOIN userSettings s ON u.userID = s.userID
AND s.settingID = 1
you can use UNION ALL clause to combine two JOINS
SELECT u.userID, u.userEmail, s.settingValue
FROM users u
LEFT userSettings s
ON u.userID = s.userID
UNION ALL
SELECT u.userID, u.userEmail, s.settingValue
FROM users u
RIGHT userSettings s
ON u.userID = s.userID

chat application friend list

I have 3 MySQL tables namely chat_comments, chat_friends and user_details and I want to display a friend list.
My tables:
chat_comments(comment_id,comment,user_id,user_id2,date_added)
chat_friends(user_id,user_id2,approved)
user_details(user_id, mainimage_id, fullname)
To do this, I need a query that will return the needed fields (u.mainimage_id, u.fullname, b.comment, b.user_id) so I can loop through the list to display a table.
SQL so far (help from #Andriy M):
SELECT
cc.comment,
cc.date_added,
u.fullname,
u.mainimage_id
FROM
user_details u
LEFT JOIN
chat_comments cc
INNER JOIN (
SELECT
user_id,
MAX(comment_id) AS maxcomment
FROM chat_comments WHERE user_id=2020 OR user_id2=2020
GROUP BY user_id
) a ON a.user_id = cc.user_id
AND a.maxcomment = cc.comment_id
ON a.user_id = u.user_id
WHERE u.user_id IN (
SELECT user_id2
FROM chat_friends
WHERE user_id = 2020
AND approved = 1
)
The above query returns the last comment made by the logged-in user's friends in conversation not the last comment between the logged-in user and his/her friend regardless of who made it.
I would like it to return the last comment between the logged-in user and their friend individually regardless of who made it. In the chat_messages table, user_id is the sender and user_id2 is the receiver. Hope it makes sense?
Like #imm said in a comment, you need to use an outer join. In case of a left join, the user_details table should become the left side of the join, the right side being the result of your inner join of chat_comments with your a derived table. You'll also need to remove the user_id IN (…) condition from inside the a subselect and re-apply it to the user_details table. Here:
SELECT
cc.comment,
cc.date_added,
u.fullname,
u.mainimage_id
FROM
user_details u
LEFT JOIN
chat_comments cc
INNER JOIN (
SELECT
user_id,
MAX(comment_id) AS maxcomment
FROM chat_comments
GROUP BY user_id
) a ON a.user_id = cc.user_id
AND a.maxcomment = cc.comment_id
ON a.user_id = u.user_id
WHERE u.user_id IN (
SELECT user_id2
FROM chat_friends
WHERE user_id = 2020
AND approved = 1
)
;
Alternatively, you could use a right join. In this case you would just need to move the user_id IN (…) condition, similarly to the LEFT JOIN solution above, and replace the second INNER JOIN with RIGHT JOIN:
SELECT
cc.comment, cc.date_added, u.fullname, u.mainimage_id
FROM
(
SELECT user_id, MAX(comment_id) AS maxcomment
FROM chat_comments
GROUP BY user_id
) a
INNER JOIN
chat_comments cc ON
a.user_id = cc.user_id AND
a.maxcomment = cc.comment_id
RIGHT JOIN
user_details u ON
a.user_id = u.user_id
WHERE u.user_id IN (select user_id2 from chat_friends where user_id=2020 AND approved=1)