I
I
Igor A2018-01-05 01:46:05
MySQL
Igor A, 2018-01-05 01:46:05

What is faster and less loaded JOIN or WHERE IN?

Good day dear!
There are users, user publications and subscriptions.
Which of the queries will be less loaded to affect the state of the mysql database.
It is necessary to display a list of publications of my subscriptions on the page. Let's say I subscribed to 2000 users and want to see their feed. The situation with WHERE IN(id,id,id......) is clear and not very nice.
I did it by analogy through JOIN and I don’t like it either, nothing comes to mind yet ...
Structure

CREATE TABLE `friends` (
  `from_id` INTEGER(11) UNSIGNED NOT NULL,
  `to_id` INTEGER(11) UNSIGNED NOT NULL,
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP,
) ;

CREATE TABLE `feed` (
  `user_id` BIGINT(20) UNSIGNED NOT NULL COMMENT 'пользователь',
  `type` TINYINT(3) UNSIGNED NOT NULL COMMENT '1 - публикации, 2 - фотки',
  `obj_id` BIGINT(20) DEFAULT NULL COMMENT 'id - объекта',
  `created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT 'дата события',
)

JOIN example
select distinct 
  `f.type`, -- тип публикации (фото/текст/.....)
  `f.obj_id`, -- id публикации
  `fs.from_id`, -- мой ID в подписках (выбираю всех юзеров за кем слежу)
from feed as f -- таблица с ID публикаций
join friends as fs on fs.from_id = f.user_id -- таблица подписок
order by `f.created_at` desc -- сортировка по дате
limit 30

Example with IN
select distinct 
  type,
  obj_id,
  user_id,
  created_at
from feed 
where user_id in (
  select to_id from friends where from_id = :user_id
)
order by created_at desc -- сортировка по дате
limit 30

Duplicates are displayed due to JOIN , I get rid of them in a not tricky way using distinct .
Perhaps through GROUP BY it will be more correct, but so far I don’t see the difference ...

Answer the question

In order to leave comments, you need to log in

3 answer(s)
1
1001001, 2018-01-05
@1001001

EXPLAIN to help you. Probably the query plan will be the same.

A
Alexey Vinogradov, 2018-01-05
@Vinstrok

Measure the script execution speed)
$start = microtime(true);
// script body
echo 'Script execution time: '.(microtime(true) - $start).' sec.'
And everything will be clear

C
Carry, 2018-01-05
@carryx

EXISTS?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question