UPDATE: Added the query that runs second most:
(maybe needed when taking an index in consideration???)
SELECT m.time, m.message, m.receiver_uid AS receiver, m.sender_uid AS sender
FROM messages AS m, users AS u
WHERE u.uid = '$coID'
AND ( (m.receiver_uid = '$meID' AND m.sender_uid = '$coID') OR
(m.receiver_uid = '$coID' AND m.sender_uid = '$meID') )
ORDER BY m.time DESC
$meID is the iD of the user who runs the wuery,
$coID is the ID of the contact.
I've got a somewhat big query and it runs everytime an user visits my page.
SELECT m2.message, m2.time, m2.sender_uid AS sender, m2.receiver_uid AS receiver,
m.contact, u.ufirstname
FROM ( SELECT CASE
WHEN sender_uid = '$me' THEN receiver_uid
ELSE sender_uid
END AS contact,
MAX(time) AS maxtime
FROM messages
WHERE sender_uid = '$me' OR receiver_uid = '$me'
GROUP BY CASE
WHEN sender_uid = '$me' THEN receiver_uid
ELSE sender_uid
END ) AS m
INNER JOIN messages m2 ON m.maxtime = m2.time
AND ((m2.sender_uid = '$me' AND m2.receiver_uid = m.Contact)
OR (m2.receiver_uid = '$me' AND m2.sender_uid = m.Contact))
INNER JOIN users AS u ON m.contact = u.uid
ORDER BY time DESC
$me is the ID of the user who runs the query
This query will (successfully) retrieve:
LAST MESSAGE from EVERY 'CONVERSATION' ordered by TIME.
So it will get the last message (whether the message is send or received) in every PM session
And than sort those by time, and retrieves the contacts information.
Please tell me if I didn't explain it correctly.
My MySQL table looks like this:
receiver_id | sender_id | message | time
From what index(es) would this query benefit?
(The user table already has an primary key on the ID so the part where the join retrieves the contacts name should be efficient)
EXPLAIN OUTPUTs:
The BIG query:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY <derived2> ALL NULL NULL NULL NULL 4 Using temporary; Using filesort
1 PRIMARY m2 ALL NULL NULL NULL NULL 42 Using where
1 PRIMARY u eq_ref PRIMARY PRIMARY 4 m.contact 1 Using where
2 DERIVED messages ALL NULL NULL NULL NULL 42 Using where; Using temporary; Using filesort
The query in the update part:
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE u const PRIMARY PRIMARY 4 const 1 Using index; Using filesort
1 SIMPLE m ALL NULL NULL NULL NULL 42 Using where
As your messages table grows, this query will start becoming slower and slower. Depending on the number of conversations that the user is a part of, you will start seeing exponentially decaying performance. While an individual index on messages.time, messages.sender_uid and messages.receiver_uid will help for now, no index will help you in your long run, unless you trim your messages table. Especially when you have more than a few hundred thousand messages.
I would suggest maintaining an association type type that links a user to a conversation and their last message id. Something looking like:
user_id | conversation_id | message_id
You then look up this table, instead of performing a complicated and expensive query. This greatly reduces the number of scans that you need to do on your messages table. While, it does slightly increase the complexity, the performance will not degrade as much as your query above.
I found by trail and error that indexing the time decreases the load time.
So that will probably be the answer to my question.
Related
I have this short snippet of code
SELECT candidate.ID
FROM users u
JOIN users candidate ON candidate.a = u.a AND candidate.b < 1
JOIN user_meta meta ON candidate.id = meta.user_id
WHERE u.id = 1
AND candidate.count > 0
ORDER BY meta.updated_at DESC
LIMIT 100
And it finishes in around 8s which I think is far to slow so I started to investigate a bit. I tried experiment with the join conditions
SELECT candidate.ID
FROM users u
JOIN users candidate ON candidate.a = u.a AND candidate.b < 2
JOIN user_meta meta ON candidate.id = meta.user_id
WHERE u.id = 1
AND candidate.count > 0
ORDER BY meta.updated_at DESC
LIMIT 100
and interesting enough this finishes in ~80ms. The only thing changed is the less than 1 to a less than 2.
Running EXPLAIN on the query yields the following for both queries
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE u const PRIMARY,index_a PRIMARY 4 const 1 NULL
1 SIMPLE meta index PRIMARY index_meta_on_updated_at 5 NULL 100 Using index
1 SIMPLE candidate eq_ref PRIMARY,index_a PRIMARY 4 db.meta.user_id 1 Using where
Probably something I have missed but what can cause this behavior?
Could you provide more information about:
- The table ( you can use describe )
- How many records has every table
- Does the tables has index ?
For troubleshooting you can use in MySQL the explain extended like Mjh told you. Provide us the explain for every query this will help us give you a better advice or even help you to make your query better.
My SQL is
SELECT authors.*, COUNT(*) FROM authors
INNER JOIN resources_authors ON authors.author_id=resources_authors.author_id
WHERE
resource_id IN
(SELECT resource_id FROM resources_authors WHERE author_id = '1313')
AND authors.author_id != '1313'
GROUP BY authors.author_id`
I have indexes on all the fields in the query, but I still get a Using temporary; Using Filesort.
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY authors ALL PRIMARY NULL NULL NULL 16025 Using where; Using temporary; Using filesort
1 PRIMARY resources_authors ref author_id author_id 4 authors.author_id 3 Using where
2 DEPENDENT SUBQUERY resources_authors unique_subquery resource_id,author_id,resource_id_2 resource_id 156 func,const 1 Using index; Using where
How can I improve my query, or table structure, to speed this query up?
There's an SQL Fiddle here, if you'd like to experiment: http://sqlfiddle.com/#!2/96d57/2/0
I would approach it a different way by doing a "PreQuery". Get a list of all authors who have have a common resource count to another author, but to NOT include the original author in the final list. Once those authors are determined, get their name/contact info and the total count of common resources, but not the SPECIFIC resources that were in common. That would be a slightly different query.
Now, the query. to help optimize the query, I would have two indexes on
one on just the (author_id)
another combination on (resource_id, author_id)
which you already have.
Now to explain the inner query. Do that part on its own first and you can see the execution plan will utilize the index. The intent here, the query starts with the resource authors but only cares about one specific author (where clause) which will keep this result set very short. That is IMMEDIATELY joined to the resource authors table again, but ONLY based on the same RESOURCE and the author IS NOT the primary one (from the where clause) giving you only those OTHER authors. By adding a COUNT(), we are now identifying how many for each respective offer have common resources, grouped by author returning one entry per author. Finally take that "PreQuery" result set (all records already prequalified above), and join to the authors. Get details and count() and done.
SELECT
A.*,
PreQuery.CommonResources
from
( SELECT
ra2.author_id,
COUNT(*) as CommonResources
FROM
resources_authors ra1
JOIN resources_authors ra2
ON ra1.resource_id = ra2.resource_id
AND NOT ra1.author_id = ra2.author_id
WHERE
ra1.author_id = 1313
GROUP BY
ra2.author_id ) PreQuery
JOIN authors A
ON PreQuery.author_id = A.author_id
i have big query like this and i can't totally rebuild application because of customer:
SELECT count(AdvertLog.id) as count,AdvertLog.advert,AdvertLog.ut_fut_tstamp_dmy as day,
AdvertLog.operation,
Advert.allow_clicks,
Advert.slogan as name,
AdvertLog.log,
(User.tx_reality_credit
+-20
-(SELECT COUNT(advert_log.id) FROM advert_log WHERE ut_fut_tstamp_dmy <= day AND operation = 0 AND advert IN (168))
+(SELECT IF(ISNULL(SUM(log)),0,SUM(log)) FROM advert_log WHERE ut_fut_tstamp_dmy <= day AND operation IN (1, 2) AND advert = 40341 )) AS points
FROM `advert_log` AS AdvertLog
LEFT JOIN `tx_reality_advert` Advert ON Advert.uid = AdvertLog.advert
LEFT JOIN `fe_users` AS User ON (User.uid = Advert.user or User.uid = AdvertLog.advert)
WHERE User.uid = 40341 and AdvertLog.id>0
GROUP BY AdvertLog.ut_fut_tstamp_dmy, AdvertLog.advert
ORDER BY AdvertLog.ut_fut_tstamp_dmy_12 DESC,AdvertLog.operation,count DESC,name
LIMIT 0, 15
It takes 1.5s approximately which is too long.
Indexes:
User.uid
AdvertLog.advert
AdvertLog.operation
AdvertLog.advert
AdvertLog.ut_fut_tstamp_dmy
AdvertLog.id
Advert.user
AdvertLog.log
Output of Explain:
id select_type table type possible_keys key key_len ref rows Extra
1 PRIMARY User const PRIMARY PRIMARY 4 const 1 Using temporary; Using filesort
1 PRIMARY AdvertLog range PRIMARY,advert PRIMARY 4 NULL 21427 Using where
1 PRIMARY Advert eq_ref PRIMARY PRIMARY 4 etrend.AdvertLog.advert 1 Using where
3 DEPENDENT SUBQUERY advert_log ref ut_fut_tstamp_dmy,operation,advert advert 5 const 1 Using where
2 DEPENDENT SUBQUERY advert_log index_merge ut_fut_tstamp_dmy,operation,advert advert,operation 5,2 NULL 222 Using intersect(advert,operation); Using where
Can anyone help me, because i tried different things but no improvements
The query is pretty large, and I'd expect this to take a fair bit of time, but you could try adding an index on Advert.uid, if it's not present. Other than that, someone with much better SQL-foo than I will have to answer this.
First, your WHERE clause is based on a specific "User.ID", yet there is an index on the Advert_Log by the Advert (user ID). So, first, change the WHERE clause to reflect this...
Where
AdverLog.Advert = 40341
Then, remove the "LEFT JOIN" to just a "JOIN" to the user table.
Finally (without a full rewrite of the query), I would tack on the "STRAIGHT_JOIN" keyword...
select STRAIGHT_JOIN
... rest of query ...
Which tells the optimizer to perform the query in the order / relations explicitly stated.
Another area to optimize would be to pre-query the "points" (counts and logs based on advert and operation) once and pull the answer from that (as a subquery) instead of it running through two queries)... but I'd be interested to know impact of above WHERE, JOIN and STRAIGHT_JOIN helps.
Additionally, looking at the join to the user table based on EITHER The Advert_Log.Advert (userID), or the TX_Reality_Credit.User (another user ID which does not appear to be the same since the join between Advert_Log and TX_Reality_Credit (TRC) is based on the TRC.UID) unless that is an incorrect assumption. This could possibly give erroneous results as you are testing for MULTIPLE User IDs... the advert user, and whoever else is the "user" from the "TRC" table... which would result in which user's credit is being applied to the "points" calculation.
To better understand the relationship and context, can you give some more clarification of what is IN these tables from the Advert_Log to TX_Reality_Credit perspective, and the Advert vs UID vs User...
SELECT vt.vtid, vt.tag, vt.typeid, vt.id, vt.count, tt.type, u.username, vt.date_added, tc.context, tc.contextid
FROM ( vt, tt, u )
LEFT JOIN tc ON ( vt.vtid = tc.vtid AND tc.userid = vt.userid )
WHERE vt.typeid = tt.typeid
AND vt.verified =0
AND vt.userid = u.userid
ORDER BY vt.date_added DESC
LIMIT 1
takes .0007s to complete
id select_type table type possible_keys key key_len ref rows Extra
1 SIMPLE vt ref typeid,userid,verified verified 1 const 9 Using where; Using filesort
1 SIMPLE tt eq_ref PRIMARY PRIMARY 4 vt.typeid 1
1 SIMPLE tc ref vtid vtid 4 vt.vtid 3
1 SIMPLE u eq_ref PRIMARY PRIMARY 4 vt.userid 1 Using where
How can I change this to not show up in the slow query log?
Just a guess. It's possible that you set log-queries-not-using-indexes flag. According to documentation, it may cause queries to be logged in slow log even if indexes are used.
I'm pretty sure that a1ex07 is correct.
However if you want to speed this query up slightly you can change your index on tc from being an index on vtid to being an index on (vtid, userid). Compound keys like that are much faster if you're joining on both keys, and are almost exactly as fast if you're just joining on the first field.
I have some querys using views, and these run a lot slower than I would expect them to given all relevant tables are indexed (and not that large anyway).
I hope I can explain this:
My main Query looks like this (grossly simplified)
select [stuff] from orders as ord
left join calc_order_status as ors on (ors.order_id = ord.id)
calc_order_status is a view, defined thusly:
create view calc_order_status as
select ord.id AS order_id,
(sum(itm.items * itm.item_price) + ord.delivery_cost) AS total_total
from orders ord
left join order_items itm on itm.order_id = ord.id
group by ord.id
Orders (ord) contain orders, order_items contain the individual items associated with each order and their prices.
All tables are properly indexed, BUT the thing runs slowly and when I do a EXPLAIN I get
# id select_type table type possible_keys key key_len ref rows Extra
1 1 PRIMARY ord ALL customer_id NULL NULL NULL 1002 Using temporary; Using filesort
2 1 PRIMARY <derived2> ALL NULL NULL NULL NULL 1002
3 1 PRIMARY cus eq_ref PRIMARY PRIMARY 4 db135147_2.ord.customer_id 1 Using where
4 2 DERIVED ord ALL NULL NULL NULL NULL 1002 Using temporary; Using filesort
5 2 DERIVED itm ref order_id order_id 4 db135147_2.ord.id 2
My guess is, "derived2" refers to the view. The individual items (itm) seem to work fine, indexed by order _ id. The problem seems to be Line # 4, which indicates that the system doesn't use a key for the orders table (ord). But in the MAIN query, the order id is already defined:
left join calc_order_status as ors on (ors.order _ id = ord.id)
and ord.id (both in the main query and within the view) refer to the primary key.
I have read somewhere than MySQL simpliy does not optimize views that well and might not utilize keys under some conditions even when available. This seems to be one of those cases.
I would appreciate any suggestions. Is there a way to force MySQL to realize "it's all simpler than you think, just use the primary key and you'll be fine"? Or are views the wrong way to go about this at all?
If it is at all possible to remove those joins remove them. Replacing them with subquerys will speed it up a lot.
you could also try running something like this to see if it has any speed difference at all.
select [stuff] from orders as ord
left join (
create view calc_order_status as
select ord.id AS order_id,
(sum(itm.items * itm.item_price) + ord.delivery_cost) AS total_total
from orders ord
left join order_items itm on itm.order_id = ord.id
group by ord.id
) as ors on (ors.order_id = ord.id)
An index is useful for finding a few rows in a big table, but when you query every row, an index just slows things down. So here MySQL probably expects to be using the whole [order] table, so it better not use an index.
You can try if it would be faster by forcing MySQL to use an index:
from orders as ord force index for join (yourindex)