我是android开发者,对mysql没有太多经验。我在mysql数据库中有3个表。
第一个表:-usertable
+-------------+-------------+----------+----------------------+
| user_id | name | image | joining_date |
+-------------+-------------+----------+----------------------+
| 100 | King | defualt.jpg | 2018-05-23 20:09:27 |
| 101 | Kochhar | defualt.jpg | 2018-05-23 20:09:27 |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
| - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - |
第二个表:-friendrequests
+-------------+-------------+----------+
| unique_id | from_id | to_id |
+-------------+-------------+----------+
| 1 | 100 | 101 |
| 2 | 200 | 110 |
| - - - - - - - - - - - - - - - - - - -|
| - - - - - - - - - - - - - - - - - - -|
第三桌:-朋友
+-------------+-------------+----------+
| unique_id | from_id | to_id |
+-------------+-------------+----------+
| 1 | 104 | 101 |
| 2 | 206 | 110 |
| - - - - - - - - - - - - - - - - - - -|
| - - - - - - - - - - - - - - - - - - -|
我想得到的用户名单谁不是我的朋友,而且我们还没有挂起朋友的要求。所以我试着跟着query:-
SELECT usertable.name,
usertable.user_id,
usertable.image
FROM `UserTable` AS usertable
WHERE usertable.user_id <> '100'
AND (SELECT Count(*)
FROM friendrequests
WHERE ( to_id = '100'
AND from_id = usertable.user_id )
OR ( to_id = usertable.user_id
AND from_id = '100' )) = 0
AND (SELECT Count(*)
FROM friends
WHERE to_id = usertable.user_id
AND from_id = '100'
OR to_id = '100'
AND from_id = usertable.user_id) = 0
ORDER BY usertable.joining_date DESC
LIMIT 10
它正在工作,但需要436秒。写这个查询的正确方法是什么?
1条答案
按热度按时间nx7onnlm1#
以下是其他方法:
1) 使用
NOT IN
您在上添加了一个条件usertable.user_id
不应该在id列表中:这些id是表的所有idfriendrequests
以及friends
那些有to_id
或者from_id
= 100.根据rick james评论编辑,与无工会相同:
2) 使用
LEFT JOIN
我看到了这个答案,试着用同样的逻辑:你做一些LEFT JOIN
并添加一个条件,其中这些连接返回空值3) 使用
NOT EXISTS
```SELECT
usertable.name,
usertable.user_id,
usertable.image
FROM
UserTable
AS usertableWHERE usertable.user_id <> '100'
AND NOT EXISTS (SELECT from_id as user_id FROM friendrequests WHERE to_id = '100')
AND NOT EXISTS (SELECT to_id as user_id FROM friendrequests WHERE from_id = '100')
AND NOT EXISTS (SELECT from_id as user_id FROM friends WHERE to_id = '100')
AND NOT EXISTS (SELECT to_id as user_id FROM friends WHERE from_id = '100')
ORDER BY usertable.joining_date DESC
LIMIT 10