Skip to content
Advertisement

MariaDB loop not displaying results of query

I have a simple query:

SELECT COUNT(ud.UserID), COUNT(DISTINCT ud.ProductID)
FROM users_data AS ud
    JOIN products AS t ON t.ID = ud.ProductID
WHERE ud.UserID = '3'

Which results in:

COUNT(ud.UserID)    COUNT(DISTINCT ud.ProductID)
519                 425

When I try to include in a while or for loop:

DELIMITER //

SET @i = 0;
FOR i IN 1..10
DO SELECT COUNT(ud.UserID), COUNT(DISTINCT ud.ProductID)
  FROM users_data AS ud
    JOIN products AS t ON t.ID = ud.ProductID
  WHERE ud.UserID = (i)
END FOR
//

I get no output other than:

Query executed OK, 0 rows affected.

Is there something else I’m misssing? thank you.

Advertisement

Answer

Why do you want to use a loop? This is much better to do as a simple query:

SELECT ud.UserId, COUNT(*), COUNT(DISTINCT ud.ProductID)
FROM users_data ud 
GROUP BY ud.UserID;

If you want specific users, you can use a WHERE clause:

SELECT ud.UserId, COUNT(*), COUNT(DISTINCT ud.ProductID)
FROM users_data ud 
WHERE ud.UserId IN (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
GROUP BY ud.UserID;

Note: I don’t think the JOIN is necessary.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement