Как выбрать отдельные данные из базы данных на основе категорий

#mysql #sql

#mysql #sql

Вопрос:

У меня есть таблица в базе данных с именем posts , в которой есть пять столбцов name

 id, title , author , cata , content
  

* cata означает категории

Я хочу получить 10 строк данных разных категорий, таких как

 select * from `posts` by distinct cata
  

Что-то вроде.

например, я хочу этот результат

 1.this is gaming posts author(Mauk) cata(Gaming) content......
2.this is glossary posts author(Mauk) cata(glossary) content......
3.this is shoes posts author(Mauk) cata(shoes) content......
4.this is garments posts author(Mauk) cata(garments) content......
5.this is you tube posts author(Mauk) cata(YouTube ) content......
6.this is blogging posts author(Mauk) cata(blogging ) content......
7.this is editing posts author(Mauk) cata(editing) content......
8.this is electronics posts author(Mauk) cata(electronics) content......
9.this is programming posts author(Mauk) cata(programming ) content......
10.this is news posts author(Mauk) cata(news) content......
  

Ответ №1:

В MySQL 8 вы можете сделать:

 select p.*
from posts p
order by row_number() over (partition by cata order by id)
limit 10;
  

В более ранних версиях вы можете получить самую последнюю запись для каждой категории, выполнив:

 select p.*
from posts p
where p.id = (select max(p2.id)
              from posts p2 
              where p2.cata = p.cata
             )
limit 10;
  

Ответ №2:

Не могли бы вы проверить следующий запрос

 select distinct cata, id, title, autho, content from posts LIMIT 10
  

Ответ №3:

Вы можете использовать и объединить выбранное значение, как показано ниже top 10

 Select Top 10 'this is gaming posts '   author   '   '    cata   ' your content...'  from 
 posts order by id ;