I'm trying to limit the number of rows per field value of a given query. I've found this answered question:
here
As in the first answer of the link, I've created the following table:
create table mytab (
id int not null auto_increment primary key,
first_column int,
second_column int
) engine = myisam;
Inserted this data:
insert into mytab (first_column,second_column) values
(1,1),
(1,4),
(2,10),
(3,4),
(1,4),
(2,5),
(1,6);
And finally run this query
select
id,
first_column,
second_column,
row_num
from
(select
*,
#num := if(#first_column = first_column, #num + 1, 1) as row_num,
#first_column:=first_column as c
from mytab
order by first_column,id) as t,
(select #first_column:='',#num:=0) as r;
But instead of getting this result, where the row_num increases whenever first_column is repeated,
+----+--------------+---------------+---------+
| id | first_column | second_column | row_num |
+----+--------------+---------------+---------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 4 | 2 |
| 5 | 1 | 4 | 3 |
| 7 | 1 | 6 | 4 |
| 3 | 2 | 10 | 1 |
| 6 | 2 | 5 | 2 |
| 4 | 3 | 4 | 1 |
+----+--------------+---------------+---------+
I get this result:
+----+--------------+---------------+---------+
| id | first_column | second_column | row_num |
+----+--------------+---------------+---------+
| 1 | 1 | 1 | 1 |
| 2 | 1 | 4 | 1 |
| 5 | 1 | 4 | 1 |
| 7 | 1 | 6 | 1 |
| 3 | 2 | 10 | 1 |
| 6 | 2 | 5 | 1 |
| 4 | 3 | 4 | 1 |
+----+--------------+---------------+---------+
I literally copied the code from the link. I checked in SQL Fiddle and code works fine. I'm using XAMPP. Could that be the reason? If it is, is there any workaround to get something like the above working?
I'd really appreciate some help. Thanks in advance.
The variable assignment has to be in the sub-query.
select
id,
first_column,
second_column,
row_num
from
(select
m.*,
#num := if(#first_column = first_column, #num + 1, 1) as row_num,
#first_column:=first_column as c
from mytab m
cross join (select #first_column:='',#num:=0) r --this was in the outer query previously
order by first_column,id
) t
Related
I have a table of sport results. When using following code, the table get places according to the times.
SET #pos := 0;
UPDATE table SET Place = ( SELECT #pos := #pos + 1 ) ORDER BY Time ASC;
In case of same times (like rows 1,3 and 4,5), it updates it according to the ID-s, so the result is following:
ID | Time | Place
1 | 00:12:14 | 1
2 | 00:12:18 | 3
3 | 00:12:14 | 2
4 | 00:12:25 | 4
5 | 00:12:25 | 5
How could I update the table so, that if there is multiple rows of same time, all rows would get the best place (like in following table)?
ID | Time | Place
1 | 00:12:14 | 1
2 | 00:12:18 | 3
3 | 00:12:14 | 1
4 | 00:12:25 | 4
5 | 00:12:25 | 4
You can do it with a join of the table to a query returning for each row the number of rows less than its Time:
update tablename t inner join (
select t.id, (
select count(*) counter from tablename
where time < t.time
) counter
from tablename t
) c on c.id = t.id
set t.place = c.counter + 1;
See the demo.
Results:
| ID | Time | Place |
| --- | -------- | ----- |
| 1 | 00:12:14 | 1 |
| 2 | 00:12:18 | 3 |
| 3 | 00:12:14 | 1 |
| 4 | 00:12:25 | 4 |
| 5 | 00:12:25 | 4 |
I'm trying to make a query setting rank column by First and Second column. Like Rank over Partition which doesn't exist MySQL
For example,
From
+----+-------+--------+------+
| id | First | Second | Rank |
+----+-------+--------+------+
| 1 | a | 10 | |
| 2 | a | 9 | |
| 3 | b | 10 | |
| 4 | b | 7 | |
| 5 | a | 1 | |
| 6 | b | 1 | |
+----+-------+--------+------+
To
+----+-------+--------+------+
| id | First | Second | Rank |
+----+-------+--------+------+
| 1 | a | 10 | 3 |
| 2 | a | 9 | 2 |
| 3 | b | 10 | 3 |
| 4 | b | 7 | 2 |
| 5 | a | 1 | 1 |
| 6 | b | 1 | 1 |
+----+-------+--------+------+
The Rank doesn't continue. It starts from 1 again when it reaches the last value of 'a' of 'First' column.
And it's gotta be SET not SELECT.
I wouldn't mind using SELECT but my point is I'm not trying to retrieve data from Database but setting values.
Cheers in advance mates.
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,first CHAR(1) NOT NULL
,second INT NOT NULL
);
INSERT INTO my_table VALUES
(1,'a',10),
(2,'a',9),
(3,'b',10),
(4,'b',7),
(5,'a',1),
(6,'b',1);
SELECT id
, first
, second
, rank
FROM
( SELECT x.*
, CASE WHEN #prev = first THEN #i:=#i+1 ELSE #i:=1 END rank
, #prev:=first
FROM my_table x
, (SELECT #prev:=null,#i:=0) vars
ORDER
BY first
, second
, id
) a
ORDER
BY id;
+----+-------+--------+------+
| id | first | second | rank |
+----+-------+--------+------+
| 1 | a | 10 | 3 |
| 2 | a | 9 | 2 |
| 3 | b | 10 | 3 |
| 4 | b | 7 | 2 |
| 5 | a | 1 | 1 |
| 6 | b | 1 | 1 |
+----+-------+--------+------+
6 rows in set (0.00 sec)
Came up with a solution which I was looking for.
I'm not sure if these queries are completely safe but so far no harms.
SET #rank = 0, #First = ''
UPDATE 'Table' SET
rank = IF(#First = First, #rank:= #rank +1, #rank := 1 AND #First := First)
ORDER BY First ASC, Second;
One method is a correlated subquery. For rank() you can do:
select t.*,
(select count(*) + 1
from t t2
where t2.first = t.first and t2.second < t.second
) as rank
from t;
Ranks are tricky to handle with variables (dense_rank() and row_number() are simpler).
EDIT:
This is easy to turn into an update:
update t join
(select t.*,
(select count(*) + 1
from t t2
where t2.first = t.first and t2.second < t.second
) as new_rank
from t
) tt
on t.id = tt.id
set t.rank = tt.new_rank;
I'm looking to allow for a custom ordering logic through mySQL that allows the following data set:
+----+-----------------+------------+-------+--+
| ID | item | Popularity | Views | |
+----+-----------------+------------+-------+--+
| 1 | A special place | 3 | 10 | |
| 2 | Another title | 5 | 12 | |
| 3 | Words go here | 1 | 15 | |
| 4 | A wonder | 2 | 8 | |
+----+-----------------+------------+-------+--+
To return an order that alternates, row by row, by popularity and then by views, so the return results look like:
+----+-----------------+------------+-------+--+
| ID | item | Popularity | Views | |
+----+-----------------+------------+-------+--+
| 3 | Words go here | 1 | 15 | |
| 2 | Another title | 5 | 12 | |
| 4 | A wonder | 2 | 8 | |
| 1 | A special place | 3 | 10 | |
+----+-----------------+------------+-------+--+
Where you will see the first row returns the 'most popular', the second row returns the most views, the third row returns the second most popular, and the 4th row returns the 2nd most views.
Currently I'm gathering an entire table through mySQL twice, and then merging these results in PHP. This isn't going to cut it when the database is large. Is this possible in mysql at all?
I guess something along these lines could work. Consider the following:
DROP TABLE IF EXISTS my_table;
CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,x INT NOT NULL
,y INT NOT NULL
);
INSERT INTO my_table VALUES
(1,3,10),
(2,5,12),
(3,1,15),
(4,2, 8)
(5,4, 1);
We can rank x and y in turn, and then arrange those ranks in a single list - so will have x1,y1,x2,y2,etc - but all rows will appear twice; once for the x rank and once for the y rank...
SELECT * FROM
(
( SELECT a.*, COUNT(*) rank FROM my_table a JOIN my_table b ON b.x <= a.x GROUP BY a.id )
UNION ALL
( SELECT a.*, COUNT(*) rank FROM my_table a JOIN my_table b ON b.y <= a.y GROUP BY a.id )
) n
ORDER BY rank
+----+---+----+------+
| id | x | y | rank |
+----+---+----+------+
| 5 | 4 | 1 | 1 |
| 3 | 1 | 15 | 1 |
| 4 | 2 | 8 | 2 |
| 4 | 2 | 8 | 2 |
| 1 | 3 | 10 | 3 |
| 1 | 3 | 10 | 3 |
| 5 | 4 | 1 | 4 |
| 2 | 5 | 12 | 4 |
| 2 | 5 | 12 | 5 |
| 3 | 1 | 15 | 5 |
+----+---+----+------+
Now we can just grab the lowest rank for each id...
SELECT id
, x
, y
FROM
(
( SELECT a.*, COUNT(*) rank FROM my_table a JOIN my_table b ON b.x <= a.x GROUP BY a.id )
UNION ALL
( SELECT a.*, COUNT(*) rank FROM my_table a JOIN my_table b ON b.y <= a.y GROUP BY a.id )
) m
GROUP
BY id,x,y
ORDER
BY MIN(rank);
+----+---+----+
| id | x | y |
+----+---+----+
| 3 | 1 | 15 |
| 5 | 4 | 1 |
| 4 | 2 | 8 |
| 1 | 3 | 10 |
| 2 | 5 | 12 |
+----+---+----+
Incidentally, this should be faster with variables - but I cannot make that solution work at present - senior moment, perhaps.
Hello I would like to make event for my application that works by insert new 3 record for 1 userID every midnight so the quantity of rows must have
n x 3 n is userIDs
+---------+-----------+-------+------------+------+----------+-------------+-------+
| userID | userNAME | chaID | chaNAME | goal | gender | row_number | dummy |
+---------+-----------+-------+------------+------+----------+-------------+-------+
| 1 | Nanyang | 1 | blahblah | 1 | 2 | 1 | 1 |
| 1 | Nanyang | 21 | something | 1 | 2 | 2 | 1 |
| 1 | Nanyang | 2 | anything | 1 | 2 | 3 | 1 |
| 2 | Julie | 3 | x | 2 | 1 | 1 | 2 |
| 2 | Julie | 12 | y | 2 | 1 | 2 | 2 |
| 2 | Julie | 23 | z | 2 | 1 | 3 | 2 |
| 3 | Kingkong | 4 | a | 1 | 2 | 1 | 3 |
| 3 | Kingkong | 5 | b | 1 | 2 | 2 | 3 |
| 3 | Kingkong | 6 | c | 1 | 2 | 3 | 3 |
+---------+-----------+-------+------------+------+----------+-------------+-------+
the row_number will be looped until they're <= 3
from my written ..
set #num := 0, #type := ‘';
CREATE TABLE random
as
(
SELECT
*
FROM (
select userID,userNAME, chaID, chaNAME,goal,gender,
#num := if(#type = userID, #num +1,1) as row_number,
#type := userID as dummy
from userchar
order by userID
) as x where x.row_number <= 3)
Anyway I used to try to create table with Select the first/least/max row per group in SQL
and it works very well and get the result like i shown. then I need to insert into in event instead of create table so i got this code below.. because I can't use SET #parameterfor insert
INSERT INTO random(userID, userNAME, chaID, chaNAME, goal, gender,row_number,dummy,status)
select *
from (select userID, userNAME, chaID, chaNAME, goal, gender,
(#num := if(#type = userID, #num +1,1)
) as row_number,
userID as dummy,
#stat as status
from hb_usercha u cross join
(select #type = '', #num := 0, #stat := '') params
order by userID,rand()
)
where row_number <= 3;
and this is a result what I got
+---------+-----------+-------+------------+------+----------+-------------+-------+
| userID | userNAME | chaID | chaNAME | goal | gender | row_number | dummy |
+---------+-----------+-------+------------+------+----------+-------------+-------+
| 1 | Nanyang | 1 | blahblah | 1 | 2 | 1 | 1 |
| 1 | Nanyang | 21 | something | 1 | 2 | 1 | 1 |
| 1 | Nanyang | 2 | anything | 1 | 2 | 1 | 1 |
| 1 | Nanyang | 3 | s | 2 | 1 | 1 | 1 |
| 1 | Nanyang | 12 | o | 2 | 1 | 1 | 1 |
| 1 | Nanyang | 23 | m | 2 | 1 | 1 | 1 |
| 1 | Nanyang | 4 | e | 1 | 2 | 1 | 1 |
| 2 | Julie | 5 | xoxo | 1 | 2 | 1 | 2 |
| 2 | Julie | 6 | xxx | 1 | 2 | 1 | 2 |
+---------+-----------+-------+------------+------+----------+-------------+-------+
.
.
.
.
It seems row_number loop isn't working
And I have no idea what's happening
Both code are same just changed parameters path
So It would be very good if someone can explain to me
Thank you so much
Assuming you want to do it for all users exists in user_char table.
Using Union all to get 3 records of each user and store the result in temporary table.
DELIMITER $$
CREATE EVENT `event_run_midnight` ON SCHEDULE EVERY 24 HOUR STARTS '2016-02-09 00:00:00' ON COMPLETION NOT PRESERVE ENABLE DO
BEGIN
drop temporary table if exists temp_users_1;
create Temporary table temp_users_1
select users.*,#row_num:=#row_num+1 as row_num,userID as dummy
from(
select * from user_char
union all
select * from user_char
union all
select * from user_char
) as users,(select #row_num:=0) as row_number
order by UserID;
/*
Copy temp table data to other temp table as MySQL
not allows to use same temp table in single query.
*/
drop temporary table if exists temp_users_2;
create Temporary table temp_users_2
select * from temp_users_1;
-- final query which returns desired output :
INSERT INTO random(userID, userNAME, chaID, chaNAME, goal, gender,row_number,dummy)
Select usr.userID,
usr.userNAME,
usr.chaID,
usr.chaNAME,
usr.goal,
usr.gender,
usr.row_num-usr_grp.min_row_num+1 as row_number,
usr.userID as dummy
from temp_users_1 usr
inner join (
Select userID,
min(row_num) as min_row_num
from temp_users_2 group by userID
) usr_grp on usr.UserID=usr_grp.userID
where usr.row_num-usr_grp.min_row_num+1 <=3; -- Condition to show only 3 records of each users.
END$$
DELIMITER ;
Updates:
1- Added Event Creation.
2- Assuming you are inserting repetitive user records into table name random.
3- This Event will execute daily at 12:00 AM.
Note:
1- You may have to change the table names if tables names are different as in answer.
2- Make sure that you have enabled MySQL Event scheduler in Configuration file otherwise event will not run automatically.
Here is the link which help you enabling MySQL event scheduler if not enabled:
http://geeksterminal.com/enable-mysql-event-scheduler-status/1711/
I have added a new column 'sums' to my table and I am trying to sum up values from 'vals' column then update 'sums' in the same table, according to the algorithm shown below in the table.
I could write a few loops in PHP but I don't think it would be nice.
Any clue how to write it nicely?
--------------------------------------------------
| id | sets | parts | vals | sums |
|-------|---------|---------|----------|---------|
| 1 | 1 | 1 | 2 | 2 |
|-------|---------|---------|----------|---------|
| 2 | 1 | 2 | 3 | 2+3=5 |
|-------|---------|---------|----------|---------|
| 3 | 1 | 3 | 5 |2+3+5=10 |
|-------|---------|---------|----------|---------|
| 4 | 2 | 1 | 4 | 4 |
|-------|---------|---------|----------|---------|
| 5 | 2 | 2 | 1 | 4+1=5 |
|-------|---------|---------|----------|---------|
| 6 | 2 | 3 | 2 | 4+1+2=7 |
|-------|---------|---------|----------|---------|
| 7 | 3 | 1 | 6 | 6 |
|-------|---------|---------|----------|---------|
This should return the value you want for sums:
SELECT t.id
, IF(t.sets=#prev_sets,#i:=#i+t.vals,#i:=t.vals) AS `sums`
, #prev_sets := t.sets AS prev_sets
FROM mytable t
JOIN (SELECT #prev_sets := NULL, #i := 0 ) i
ORDER BY t.sets, t.parts
You can use this as an inline view in an update statement
UPDATE ( SELECT t.id
, IF(t.sets=#prev_sets,#i:=#i+t.vals,#i:=t.vals) AS `sums`
, #prev_sets := t.sets AS prev_sets
FROM mytable t
JOIN (SELECT #prev_sets := NULL, #i := 0 ) i
ORDER BY t.sets, t.parts
) s
JOIN mytable r
ON r.id = s.id
SET r.sums = s.sums
From the example data, it looks like you want the "groupings" on sets, and you want to order on parts within each group.