S
S
stikname2017-04-10 20:46:12
MySQL
stikname, 2017-04-10 20:46:12

How to make a selection from a mysql database of records and a table of links with categories?

Good day gentlemen, tell me the following question, how to implement a selection from the database of the following form: http://sqlfiddle.com/#!9/f62496/2
What we have:
1. Table of records
2. Table of categories
3. Table of links between records and categories
Almost all entries have several categories.
It is necessary to implement 3 fastest MySQL queries and put down indexes:
1. Selecting 10 records with a certain category, for example 2, sorting by the date field and the condition date <= 1491502307 AND approve = 1
2. Selecting 10 records in which there are simultaneously three categories, for example 2,4,6 (the number of categories may be different), sorted in descending order by the number of matches. Condition (date <= 1491502307 AND approve = 1) example: sqlfiddle.com/#!9/aa8497/4 . In this example, the selection is made in three categories (maybe more) and the records from the database are displayed sorted by the number of matches, in descending order. This is the maximum I could do.
3. What indexes need to be put down for sampling acceleration?
There are solutions, but it seems that they are far from ideal.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
entermix, 2017-04-10
@entermix

one.
2.
OR
3. Indexes for post2cat:

-- Индексы таблицы `post2cat`

ALTER TABLE `post2cat`
  ADD PRIMARY KEY (`id_post`,`id_category`),
  ADD KEY `fk_id_post` (`id_post`) USING BTREE,
  ADD KEY `fk_id_category` (`id_category`) USING BTREE;

--
-- Ограничения внешнего ключа таблицы `post2cat`
--
ALTER TABLE `post2cat`
  ADD CONSTRAINT `post2cat_ifbk_1` FOREIGN KEY (`id_post`) REFERENCES `post` (`id`) ON DELETE CASCADE,
  ADD CONSTRAINT `post2cat_ifbk_2` FOREIGN KEY (`id_category`) REFERENCES `category` (`id`) ON DELETE CASCADE;

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question