Created
June 9, 2021 21:58
-
-
Save surfmuggle/7d23b543739cd4f4af8674238e363979 to your computer and use it in GitHub Desktop.
Stackoverflow Question - Select where id in variable does not work
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
CREATE TABLE Users (ID int, Username varchar(100), isActive TINYINT); | |
CREATE TABLE UserActions (ID int, User_ID int, Type varchar(100), ActionDate Date); | |
INSERT INTO | |
Users(ID, Username, isActive) | |
VALUES | |
(1, 'Ben Busy',1), | |
(2, 'Lui Lazy',1), | |
(3, 'Emmy Eager',1), | |
(4, 'Lana Later',1); | |
INSERT INTO | |
UserActions(ID, User_ID, Type, ActionDate) | |
VALUES | |
(1, 1, 'Login', '2021-01-01'), | |
(2, 3, 'Login', '2021-01-02'), | |
(3, 1, 'Login', '2021-01-02'), | |
(4, 1, 'Login', '2021-01-03'); | |
SELECT u.ID, u.Username, ua.ActionDate FROM Users u LEFT JOIN UserActions ua | |
ON u.ID = ua.User_ID | |
AND (ua.Type = "Login" OR ua.Type = NULL); | |
SET @userIDs := ( | |
SELECT GROUP_CONCAT(u.ID SEPARATOR ', ') FROM Users u LEFT JOIN UserActions ua | |
ON u.ID = ua.User_ID | |
AND (ua.Type = "Login" OR ua.Type = NULL) | |
WHERE ua.ActionDate IS NULL); | |
SELECT @userIDs; | |
SELECT * FROM Users WHERE ID in (@userIDs); -- only retunrs Lui Lazy but not Lana Later |
This is my attempt to avoid a temp table
UPDATE Users INNER JOIN
(
SELECT u.ID FROM Users u LEFT JOIN UserActions ua
ON u.ID = ua.User_ID AND (ua.Type = "Login" OR ua.Type = NULL)
WHERE ua.ActionDate IS NULL
) as subquery
ON u.ID = subquery.ID set u.ID = 0;
but it was not running on fiddle (time out)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
See sqlfiddle under http://sqlfiddle.com/#!9/3563eef/8