SELECT u.id, u.honour, COUNT(*) + 1 AS rank
FROM user_info u
INNER JOIN user_info u2
ON u.honour < u2.honour
WHERE u.id = '$id'
AND u2.status = 'Alive'
AND u2.rank != '14'
This query is currently utterly slowing down my server. It works out based on your honour what rank you are within the 'user_info' table which stores it out of all our users.
Screenshot for explain.
http://cl.ly/370z0v2Y3v2X1t1r1k2A
SELECT u.id, u.honour, COUNT(*)+1 as rank
FROM user_info u
USE INDEX (prestigeOptimiser)
INNER JOIN user_info u2
ON u.honour < u2.honour
WHERE u.id='3'
AND u2.status='Alive'
AND u2.rank!='14'
I think the load comes from your join condition '<'.
You could try to split your query or (or if you prefer a subquery) and use the honour index for the count.
SELECT id, honour INTO #uid, #uhonour
FROM user_info
WHERE id = '$id';
SELECT #uid, #uhonour, COUNT(honour) + 1 as rank
FROM user_info
WHERE status = 'Alive'
AND rank != '14'
AND #uhonour < honour;
Firstly, you should add a group by clause so that your query makes sense.
Secondly, you should change the status column to hold an integer to make the index smaller.
Thirdly, you should create an index on id and status like this:
alter table user_info add index idxID_Status (id, status)
Finally, to obtain ranks you should take a look at this answer. Additionally you should add a way to order them... getting a rank without order is not really a rank.
As we can see from explain, MySQL uses the wrong index here. To start with, just drop all indexes and create a new one, containing at least these two fields: Id and Honour. It should boost up performance considerably.
ALTER TABLE user_info ADD INDEX myIndex (id, honour);
Related
Hi I have pagination in angular js in my app, I send the data to my big query that includes the filters that the user set
UPDATE
SQL_CALC_FOUND_ROWS this is my problem. How do I count the rows of specific filters . It is took me 2 second for 100,000 rows I need the number for the pagination as a total number
UPDATE:
I have the following inner query that I missed here :
(select count(*) from students as inner_st where st.name = inner_st.name) as names,
when I remove above inner query is much faster
rows: 50,000
Users table : 4 rows
Classes table : 4 rows
indexes: only id as primary key
query time 20-40 seconds
tables: students.
columns : id, date ,class, name,image,status,user_id,active
table user
coloumn: id,full_name,is_admin
query
SELECT SQL_CALC_FOUND_ROWS st.id,
st.date,
st.image,
st.user_id,
st.status,
st,
ck.name AS class_name,
users.full_name,
(select count(*) from students AS inner_st where st.name = inner_st.name) AS names,
FROM students AS st
LEFT JOIN users ON st.user_id = users.user_id
LEFT JOIN classes AS ck ON st.class = ck.id
WHERE date BETWEEN '2018-01-17' AND DATE_ADD('2018-01-17', INTERVAL 1 DAY)
AND DATE_FORMAT(date,'%H:%i') >= '00:00'
AND DATE_FORMAT(date,'%H:%i') <= '23:59'
AND st.active=1
-- here I can concat filters from web like "and class= 1"
ORDER BY st.date DESC
LIMIT 0, 10
How can I make it faster? when I delete the order by and SQL_CALC_FOUND_ROWS it faster but i need them
I heard about indexes but only primary key is index
Few comments before recommending a different approach to this query:
Did you consider removing SQL_CALC_FOUND_ROWS and instead running two queries (one that counts and one that selects the data)? In some cases it might be quicker than joining them both to one query.
What is the goal of these conditions? What are you trying to achieve? Can we remove them (as it seems they might always return true?) - AND DATE_FORMAT(st.date, '%H:%i') >= '00:00' AND DATE_FORMAT(st.date, '%H:%i') <= '23:59'
You only need 10 results, but the database will have to run the "names" subquery for each of the results before the LIMIT (which might be a lot?). Therefore, I would recommend to extract the subquery from the SELECT clause to a temporary table, index it and join to it (see fixed query below).
To optimize the query, let's begin with adding these indexes:
ALTER TABLE `classes` ADD INDEX `classes_index_1` (`id`, `name`);
ALTER TABLE `students` ADD INDEX `students_index_1` (`active`, `user_id`, `class`, `name`, `date`);
ALTER TABLE `users` ADD INDEX `users_index_1` (`user_id`, `full_name`);
Now create the temporary table (originally this was a subquery in the SELECT clause) and index it:
-- Transformed subquery to a temp table to improve performance
CREATE TEMPORARY TABLE IF NOT EXISTS temp1 AS SELECT
count(*) AS names,
name
FROM
students AS inner_st
WHERE
1 = 1
GROUP BY
name
ORDER BY
NULL
-- This index is required for optimal temp tables performance
ALTER TABLE
`temp1`
ADD
INDEX `temp1_index_1` (`name`, `names`);
And the modified query:
SELECT
SQL_CALC_FOUND_ROWS st.id,
st.date,
st.image,
st.user_id,
st.status,
ck.name AS class_name,
users.full_name,
temp1.names
FROM
students AS st
LEFT JOIN
users
ON st.user_id = users.user_id
LEFT JOIN
classes AS ck
ON st.class = ck.id
LEFT JOIN
temp1
ON st.name = temp1.name
WHERE
st.date BETWEEN '2018-01-17' AND DATE_ADD('2018-01-17', INTERVAL 1 DAY)
AND st.active = 1
ORDER BY
st.date DESC LIMIT 0,
10
Give this a try first:
INDEX(active, date)
Is user_id the PK for users? Is class_id the PK for classes? If not, then they should be INDEXed.
Why are you testing the times separate?
Fix the test so it is obvious which table each column is in.
Do you really need LEFT JOIN? Or would JOIN suffice? In the latter case, there are more optimization options.
Give some realistic examples of other SELECTs; different index(es) may be needed.
Is the "first" page slow? Or only later pages? See this for pagination optimization -- by not using OFFSET.
I need to write a query that will pull all pieces of hardware that are unassigned to a user. My tables that look like this:
table: hardware
ID, brand, date_of_purchase, purchase_price, serial_number, invoice_location
table: assigned_equipment
ID, user_id, object_id, object_type, is_assigned, date_assigned
Once a piece of hardware is checked out to a user, a new entry in assigned_equipment is made, and the column is_assigned is set to 1. It can be 0 if it is later unassigned.
That being said, my query looks like this:
SELECT * FROM hardware WHERE ID NOT IN (SELECT object_id FROM assigned_equipment);
I need a conditional statement that would add WHERE is_assigned = 0 otherwise if there's an entry it will not list. Ideas?
Simple extend the subquery to contain only assigned items:
SELECT * FROM hardware
WHERE ID NOT IN
(SELECT object_id FROM assigned_equipment WHERE is_assigned = 1);
So, every matching id is NOT in the subselect - therefore unassigned.
Columns in the assignment table with is_assigned=0 are no longer part of the subresult, and therefore part of your outer result.
You can't do this without a JOIN so you should ditch the subselect.
SELECT
hardware.*
FROM
hardware h
LEFT JOIN
assigned_equipment e
ON (e.object_id = h.id)
WHERE
e.id IS NULL
OR
(e.is_assigned = 0 AND e.user_id = ?);
If you take a semantic approach then the is_assigned column should not be required - as only assigned items should appear in the assigned_equipment table.
Which would make your query:
SELECT *
FROM `hardware`
WHERE `id` NOT IN (
SELECT `object_id`
FROM `assigned_equipment`
);
This of course means that when an item becomes unassigned you DELETE the row from the assigned_equipment table.
In my opinion this is better as it means you're not storing unnecessary data.
I am using mysql and this is a query that I quickly wrote, but I feel this can be optimized using JOINS. This is an example btw.
users table:
id user_name first_name last_name email password
1 bobyxl Bob Cox bob#gmail.com pass
player table
id role player_name user_id server_id racial_name
3 0 boby123 1 2 Klingon
1 1 example 2 2 Race
2 0 boby2 1 1 Klingon
SQL
SELECT `player`.`server_id`,`player`.`id`,`player`.`player_name`,`player`.`racial_name`
FROM `player`,`users`
WHERE `users`.`id` = 1
and `users`.`id` = `player`.`user_id`
I know I can use a left join but what are the benefits
SELECT `player`.`server_id`,`player`.`id`,`player`.`player_name`,`player`.`racial_name`
FROM `player`
LEFT JOIN `users`
ON `users`.`id` = `player`.`user_id`
WHERE `users`.`id` = 1
What are the benefits, I get the same results ether way.
Your query has a JOIN in it. It is the same as writing:
SELECT `player`.`server_id`,`player`.`id`,`player`.`player_name`,`player`.`racial_name`
FROM `player`
INNER JOIN `users` ON `users`.`id` = `player`.`user_id`
WHERE `users`.`id` = 1
The only reason for you to use left join is if you want to get data from player table even when you don't have matches in users table.
LEFT JOIN will get data from the left table even if there's no equal data from the right side table.
I guess at one point, that player table's data will not be equivalent to users table specially if the data on users table has not been inserted into player table.
Your first query might return null on cases that the 2nd table (player) has no equivalent data corresponding to users table.
Also, IMHO, setting up another table for servers is a good idea in terms of complying to the normalization rules in database structure. After all, what details of the server_id is the column on player table pointing to.
The first solution makes a direct product (gets and connects everything with everything) then drops away the bad results. If you have a lot of rows this will be very slow!
The left join gets first the left table then put only the matching rows from the right (or null).
In your example you don't even need join. :)
This'll give you the same result and it'll be good until you just check for user id:
SELECT `player`.`server_id`,`player`.`id`,`player`.`player_name`,`player`.`racial_name`
FROM `player`
WHERE `player`.`user_id` = 1
Another solution if you want more conditions, without join could be something like this:
SELECT * FROM player WHERE player.user_id IN (SELECT id FROM user WHERE ...... )
I have a table with user payment details, and another table with a list of users. I want to get the balance of all users from the payment details, but only for users that are not banned (which is a column in the users table).
I am somewhat new to nested queries so I am not sure how to do this?
Here is what I have tried so far...
mysql_query("
SELECT SUM(balance)
FROM payment_details
WHERE (SELECT ban
FROM users
WHERE username=username
) != '1'
")
Note: Username is a column in both tables.
The above query does not work.
To Recap: There are two tables: payment_details and users. I want to add together the balance column for all the users that are not banned.
Don't use a subquery here. Instead, use a JOIN.
SELECT SUM(payment_details.balance) FROM payment_details
JOIN users ON payment_details.username = users.username
WHERE ban != '1'
Agreed, a join is probably what you want.
However to answer the specific question, you could try a query like:
SELECT SUM(payment_details.balance)
FROM payment_details
WHERE payment_details.username in (
SELECT users.username
FROM users WHERE ban != '1'
);
Note that it wasn't clear from the question whether you wanted the sum for each individual user, or the total sum for all users. The above query provides the latter -- not grouped by user.
the query is:
SELECT SUM(balance) FROM payment_details JOIN users ON payment_details.username=users.username WHERE users.ban !='1' group by payment_details.username
by the way, working on the users ids would be much better than on the usernames
Let's say I have a table with the following columns:
p_id
userid
points
Let's say these columns have over 5000 records. So we actually have users with points. Each user has an unique row for their point record. Imagine that every user can get points on the website by clicking somewhere. When they click I update the database with the points they get.
So we have a table with over 5000 records of people who have points, right? Now I would like to order them by their points (descending), so the user with the most point will be at the top of the page if I run a MySQL query.
I could do that by simply running a query like this:
SELECT `p_id` FROM `point_table` ORDER BY `points` DESC
This query would give me all the records in a descending order by points.
Okay, here my problem comes, now (when it is ordered) I would like to display each user which place are they actually. So I'd like to give each user something like this: "You are 623 of 5374 users". The problem is that I cannot specify that "623" number.
I would like to run a query which is order the table by points it should "search" or count the row number, where their records are and than return that value to me.
Can anyone help me how to build a query for this? It would be a really big help. Thank you.
This answer should work for you:
SET #rank=0;
SELECT #rank:=#rank+1 AS rank, p_id FROM point_table ORDER BY points DESC;
Update: You might also want to consider to calculate the rank when updating the points and saving it to an additional column in the same table. That way you can also select a single user and know his rank. It depends on your use cases what makes more sense and performs better.
Update: The final solution we worked out in the comments looked like this:
SELECT
rank, p_id
FROM
(SELECT
#rank:=#rank+1 AS rank, p_id, userid
FROM
point_table, (SELECT #rank := 0) r
ORDER BY points DESC
) t
WHERE userid = intval($sessionuserid);
Row number after order by
SELECT ( #rank:=#rank + 1) AS rank, m.* from
(
SELECT a.p_id, a.userid
FROM (SELECT #rank := 0) r, point_table a
ORDER BY a.points DESC
) m
For some reason the accepted answer doesn't work for me properly - it completely ignores "ORDER BY" statement, sorting by id (primary key)
What I did instead is:
SET #rn=0;
CREATE TEMPORARY TABLE tmp SELECT * FROM point_table ORDER BY points DESC;
SELECT #rn:=#rn+1 AS rank, tmp.* FROM tmp;
Add a new column for position to the table. Run a cron job regularly which gets all the table rows ordered by points and then update the table with the positions in a while loop.