SQL-запрос для получения N элементов таблицы с повторяющимися данными

0

У меня есть запрос, который возвращает данные в этом формате

| Name | SomeData | MoreStuff | |--------|-------------|---------------| | asset1 | я need this | And also this | | asset1 | я need this | And also this | | asset1 | я need this | And also this | | asset2 | я need this | And also this | | asset2 | я need this | And also this | | asset3 | я need this | And also this | | asset3 | я need this | And also this | | asset3 | я need this | And also this | | asset4 | я need this | And also this | | asset5 | я need this | And also this | | asset5 | я need this | And also this | |...... |........... |............. |

Скажем, что мне нужно 20 разных активов, но также данные каждой строки. Здесь "LIMIT" не будет работать и с "GROUP BY".

Какие у меня есть другие варианты?

----- Редактировать ----

Например, если мне нужны 3 разных актива, то результат должен быть

| Name | SomeData | MoreStuff | |--------|-------------|---------------| | asset1 | я need this | And also this | | asset1 | я need this | And also this | | asset1 | я need this | And also this | | asset2 | я need this | And also this | | asset2 | я need this | And also this | | asset3 | я need this | And also this | | asset3 | я need this | And also this | | asset3 | я need this | And also this |

  • 1
    Опубликуйте ожидаемый результат
  • 0
    Как насчет Limit с Distinct ?
Показать ещё 1 комментарий
Теги:

4 ответа

1
Лучший ответ

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

select a.*
from demo a
join (
  select distinct Name
  from demo 
  order by Name
  limit 3
) b on a.Name = b.Name

демонстрация

1

Это позволит получить строки из первых 3-х активов без использования самостоятельного объединения:

SQL Fiddle

MySQL 5.6 Настройка схемы:

CREATE TABLE table_name (
  Name      VARCHAR(20),
  SomeData  VARCHAR(20),
  MoreStuff VARCHAR(20)
);


INSERT INTO table_name VALUES ( 'asset4', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset5', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset2', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset3', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset1', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset3', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset2', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset1', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset1', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset3', 'I need this', 'And also this' );
INSERT INTO table_name VALUES ( 'asset5', 'I need this', 'And also this' );

Запрос 1:

SELECT Name, SomeData, MoreStuff
FROM   (
  SELECT @asset_num := IF( @prev_name = t.name, @asset_num, @asset_num + 1 ) AS an,
         t.*,
         @prev_name := Name
  FROM   table_name t
         CROSS JOIN
         ( SELECT @prev_name := '', @asset_num := 0 ) r
  ORDER BY Name
) t
WHERE an <= 3

Результаты:

|   Name |    SomeData |     MoreStuff |
|--------|-------------|---------------|
| asset1 | I need this | And also this |
| asset1 | I need this | And also this |
| asset1 | I need this | And also this |
| asset2 | I need this | And also this |
| asset2 | I need this | And also this |
| asset3 | I need this | And also this |
| asset3 | I need this | And also this |
| asset3 | I need this | And also this |
  • 0
    Этот запрос работает на sql fiddle, но в моей среде он возвращает только одну строку по имени, я не понимаю, почему в таблице больше столбцов ...
1

Попробуй это:

select *
from TABLE
where Name in (
    select distinct Name 
    from TABLE
    limit 3
)
  • 0
    к сожалению это не работает, мой сервер в (позорно) версии 5.6
0

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

SELECT Name, SomeData, MoreStuff
FROM (
       SELECT  @name_number := IF(@Name = Name, @name_number + 1, 1) AS name_number, 
               @Name := Name as Name, SomeData, MoreStuff
       FROM 
              (SELECT @name_number := 1) x, 
              (SELECT SomeData, MoreStuff, @Name := Name as Name FROM your_table ORDER BY Name) y
      ) z
WHERE name_number <= 3;

Демо-версия Sql Fiddle здесь!

Ещё вопросы

Сообщество Overcoder
Наверх
Меню