【发布时间】:2017-04-20 10:05:47
【问题描述】:
我有 2 张桌子:
第一个表users:
+-------------------------+---------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+-------------------------+---------+------+-----+---------+-------+
| id | int(11) | NO | PRI | NULL | |
| first_name | text | NO | | NULL | |
| age | int(11) | YES | | NULL | |
| settings | text | YES | | NULL | |
+-------------------------+---------+------+-----+---------+-------+
第二张桌子proposals:
+---------+---------+------+-----+---------+----------------+
| Field | Type | Null | Key | Default | Extra |
+---------+---------+------+-----+---------+----------------+
| id | int(11) | NO | PRI | NULL | auto_increment |
| from_id | int(11) | NO | | NULL | |
| to_id | int(11) | NO | | NULL | |
| status | int(11) | NO | | NULL | |
+---------+---------+------+-----+---------+----------------+
我需要从id 不在to_id 中proposals 中的用户那里获得1 随机 行
我正在用这个 sql 做(没有 rand):
SELECT DISTINCT *
FROM profiles
WHERE
profiles.first_name IS NOT NULL
AND
NOT EXISTS (
SELECT *
FROM proposal
WHERE
proposal.to_id = profiles.id
)
LIMIT 0 , 1
性能很好:1 row in set (0.00 sec)
但是性能很差:1 row in set (1.78 sec) 当我在末尾添加ORDER BY RAND() 时
我在users.id 中有大漏洞,我不能使用MAX(id) 之类的东西
我尝试设置随机limit,例如:
...
LIMIT 1234 , 1;
Empty set (2.71 sec)
但这也需要很多时间:(
如何以良好的性能获得users.id 中不存在的proposals.to_id 的随机1 个用户?
我认为我需要先用rand() 获取所有profiles,然后过滤它们,但我不知道该怎么做。
【问题讨论】:
-
RAND()很难优化。但是here 是一些技巧。大多数其他技术确实涉及表扫描,这是主要的杀手。
标签: mysql sql performance