Is the GROUP BY UNIQUE command computes all groups before applying the LIMIT clause?

If I am GROUP BYin a unique way and apply the sentence LIMITto the query, will all groups be calculated before the limit is applied?

If I have one hundred records in a table (each has a unique key), will I have 100records in a temporary table created (for GROUP BY) before it is applied LIMIT?

Case study why I need it:

Take Stack Overflowfor example.

Each query that you run to display a list of questions also shows the user who asked this question and the number of icons that he has.

So, while the user ↔ question is one to one, the user ↔ icons have a lot.

The only way to do this in one query (and not in a question, and another in relation to users and then combine the results) is to group the query using the primary key (question_id) and join + group_concat into the user_badges table.

The same goes for TAGS questions.

Code example:
Table Questions:
question_id  (int)(pk)|   question_body(varchar)


Table tag-question:
question-id (int) | tag_id (int)


SELECT:

SELECT quesuestions.question_id,
       questions.question_body,
       GROUP-CONCAT(tag_id,' ') AS 'tags-ids'
FROM
       questions
   JOIN
       tag_question
   ON
       questions.question_id=tag-question.question-id
GROUP BY
       questions.question-id
LIMIT 15
+3
source share
3 answers

LIMITapplied after GROUP BY.

Whether a temporary table is created or not depends on how your indexes are created.

If you have an index in the grouping field and are not sorted by the final results, it is applied INDEX SCAN FOR GROUP BY, and each unit is calculated on the fly.

, - LIMIT, .

, , , , .

, filesort.

Update:

, , EXPLAIN EXTENDED.

, question_id PRIMARY KEY , , .

, filesort, 15'th.

, :

SELECT question_id,
       question_body,
       (
       SELECT  GROUP_CONCAT(tag_id, ' ')
       FROM    tag_question t
       WHERE   t.question_id = q.question_id
       )
FROM   questions q
ORDER BY
       question_id
LIMIT 15
  • -, ,
  • -,
  • -, ( ).
+1

, :

  • WHERE
  • GROUP
  • HAVING
  • SORT
  • SELECT
  • LIMIT

LIMIT - , , .

, , , : stackoverflow , - ..

(uid, badge_id, etc.)
(1, 2, ...)
(1, 3, ...)
(1, 12, ...)

.

, . , SUM, , .

EDIT:

- ( WHERE):

SELECT
  quesuestions.question_id,
  questions.question_body,
  GROUP_CONCAT(tag_id,' ') AS 'tags_ids'
FROM
  questions q1
  JOIN tag_question tq
    ON q1.question_id = tq.question-id
WHERE
  q1.question_id IN (
    SELECT
      tq2.question_id
    FROM
      tag_question tq2
        ON q2.question_id = tq2.question_id
      JOIN tag t
        tq2.tag_id = t.tag_id
    WHERE
      t.name = 'the-misterious-tag'
  )
GROUP BY
  q1.question_id
LIMIT 15
+4

, , , .

+1

Source: https://habr.com/ru/post/1706390/


All Articles