简体   繁体   English

MYSQL:查询中的大比较的 WHERE IN () 速度问题

[英]MYSQL: WHERE IN () speed issue for large comparison in Query

I have a serious issue with WhERE IN () condition in mysql query.我对 mysql 查询中的 WhERE IN () 条件有一个严重的问题。 I am fetching RESULT fron two tables which have not more than 10 fields.我正在从两个不超过 10 个字段的表中获取结果。 I created primary fields in both.我在两者中都创建了主要字段。

I need to use WHERE IN () to see logged_in IDs which can be more than 500 or long.我需要使用 WHERE IN () 来查看可以超过 500 或更长的登录 ID。 So it creates a heavy query and it fetches records too slow.所以它会创建一个繁重的查询并且它获取记录的速度太慢。 When there are logged_in IDs are less than 20 or so its fine but when they are more than 50 or 100 or more it becomes more slow and takes much time to process.当 login_in ID 小于 20 左右时它很好,但是当它们超过 50 或 100 或更多时,它变得更慢并且需要很多时间来处理。

So, my problm is how to make it fast?那么,我的问题是如何使其快速? Am i using wrong technique?我使用了错误的技术吗? I mean should I use something else on place of where IN()?我的意思是我应该在 IN() 的地方使用其他东西吗? Any idea would be highly appreciated.任何想法将不胜感激。

SELECT subscriber. * , track . * 
FROM track, subscriber 
WHERE track.type =1 AND 
      track.logged_in IN ( 2803, 2806, 54, 54, 64, 383, 833, 2808, 2809, 2810, 56, 2811, 2812, 2813, 2814, 2815, 2816, 2817, 2818, 2819, 2820, 2821, 2822, 2823, 2824, 2825, 2826, 2827, 2828, 2829, 2830, 2831, 2832 ) AND 
      subscriber.post_id = track.post_id AND 
      track.nmade = subscriber.nmade AND 
      subscriber.userid =  '54' 
ORDER BY track.date_created DESC 
LIMIT 5

The IN clause in mysql isn't famous by its speed ... maybe if you create a temporal table with the id's that you want and you do a JOIN with track table the operation will be faster. mysql 中的 IN 子句并不以其速度而闻名......也许如果你用你想要的 id 创建一个时态表并且你用 track 表做一个 JOIN 操作会更快。

The temporaries tables are per session, therefore you don't need spend effort dropping them after use, when you close the connection to mysql, they will be removed by the mysql.临时表是每个会话的,因此您在使用后不需要花费精力删除它们,当您关闭与 mysql 的连接时,它们将被 mysql 删除。

Anyway if you want have reasonable performance in the JOIN operation you will need index the logged_in field.无论如何,如果您想在 JOIN 操作中获得合理的性能,您将需要对 logging_in 字段进行索引。

You can try something like this, should be faster.你可以试试这样的东西,应该会更快。 This is not the best method, but may be easiest to implement into your PHP.这不是最好的方法,但可能最容易在您的 PHP 中实现。

SELECT subscriber. * , track . * 
FROM track, subscriber
JOIN (
    SELECT 2803 as logged_in
    UNION
    SELECT 2806
    UNION
    SELECT 54
    UNION
    SELECT 64
    ) list
ON track.logged_in = list.logged_in

WHERE track.type =1 AND 
      subscriber.post_id = track.post_id AND 
      track.nmade = subscriber.nmade AND 
      subscriber.userid =  '54' 
ORDER BY track.date_created DESC 
LIMIT 5

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM