Multiple LEFT JOIN in multiple tables

Nick

I have the following SQL select:

SELECT s.*,
       GROUP_CONCAT(CONCAT_WS(':', m.type, m.id, m.filename) SEPARATOR ',') AS multimedia,
       GROUP_CONCAT(CONCAT_WS(':', c.id) SEPARATOR ',') AS categories
FROM sections s 


LEFT JOIN sections_multimedia sm
     ON s.id = sm.section_id 
LEFT JOIN multimedia m
     ON sm.multimedia_id = m.id 


LEFT JOIN sections_categories sc
     ON s.id = sc.section_id 
LEFT JOIN categories c
     ON sc.category_id = c.id


WHERE s.id = s.id
GROUP BY s.id
ORDER BY s.position, s.id ASC;

As a result, the field 'categories' has the correct values, which are(2,3), but unfortunately repeated many times! (the result is: 2,2,2,2,2,2,3,3,3,3,3,3)

What is wrong with my select?

Thank you for your replies!

Thorsten Kettner

When looking for aggregates from different tables, you should always aggregate before joining:

SELECT 
  s.*,
  mul.multimedia,
  cat.categories 
FROM sections s 
LEFT JOIN
(
  SELECT
    sm.section_id,
    GROUP_CONCAT(CONCAT_WS(':', m.type, m.id, m.filename) SEPARATOR ',') AS multimedia
  FROM sections_multimedia sm
  JOIN multimedia m ON sm.multimedia_id = m.id 
  GROUP BY sm.section_id
) mul ON s.id = mul.section_id
LEFT JOIN
(
  SELECT
    sc.section_id,
    GROUP_CONCAT(CONCAT_WS(':', c.id) SEPARATOR ',') AS categories
  FROM sections_categories sc
  JOIN categories c ON sc.category_id = c.id
  GROUP BY sc.section_id
) cat ON s.id = cat.section_id;

Эта статья взята из Интернета, укажите источник при перепечатке.

Если есть какие-либо нарушения, пожалуйста, свяжитесь с[email protected] Удалить.

Отредактировано в
0

я говорю два предложения

0обзор
Войти в системуУчаствуйте в комментариях

Статьи по теме

How to make a table left outer join of multiple tables

LINQ Left Outer Join Multiple Tables with Group Count and Row Concatenation

Select same column from multiple tables with condition and LEFT JOIN

MySQL multiple LEFT JOIN возвращает повторяющиеся строки

MYSQL LEFT JOIN and multiple ORDER BY

mysql multiple COUNT () из нескольких таблиц с LEFT JOIN

LEFT JOIN multiple sub queries

Create View by Left join on multiple columns with OR

MySQL Query Multiple LEFT JOIN с столбцом WHERE NOT LIKE

Function to `interval_left_join` multiple dataframes

LInq left join with multiple condition in on clause

sql left join with multiple same table question

SQL Update Join Multiple Tables (if field exists)

Join multiple tables on one specific column

Optimizing INNER JOIN across multiple tables

LEFT JOIN with 3 TABLES запрос возвращает одну и ту же строку несколько раз

SQL count(*) issues with join on multiple tables in mysql involving an outer join

Left join in R when df1 matches multiple times

Union and left join of three tables

How to join tables on multiple columns in Power BI Desktop

Trying to join two tables with multiple where condition on both table in sql

R Data.Table: In-memory left join multiple columns from left and right side

Несколько LEFT JOINS с Multiple COUNT () подсчитывают весь столбец

Left join 3 tables error #1066

LEFT OUTER JOIN 3 TABLES -SQL SERVER

Sql left outer join with three tables

SQL Server Left Join with 3 tables

Query chaining multiple tables

Using multiple ngFor in tables

TOP список

  1. 1

    Распределение Рэлея Curve_fit на Python

  2. 2

    TypeError: store.getState não é uma função. (Em 'store.getState ()', 'store.getState' é indefinido, como posso resolver esse problema?

  3. 3

    В типе Observable <unknown> отсутствуют следующие свойства из типа Promise <any>.

  4. 4

    Как добавить Swagger в веб-API с поддержкой OData, работающий на ASP.NET Core 3.1

  5. 5

    How to click an array of links in puppeteer?

  6. 6

    Merging legends in plotly subplot

  7. 7

    ViewPager2 мигает / перезагружается при смахивании

  8. 8

    Отчеты Fabric Debug Craslytic: регистрация, отсутствует идентификатор сборки, применить плагин: io.fabric

  9. 9

    How to normalize different curves drawn with geom = "step" when using stat_summary

  10. 10

    无法通过Vue在传单中加载pixiOverlay

  11. 11

    как я могу удалить vue cli 2?

  12. 12

    Как я могу нарисовать заполненный прямоугольник в JFreeChart?

  13. 13

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

  14. 14

    Elasticsearch - Нечеткий поиск не дает предложения

  15. 15

    Single legend for Plotly subplot for line plots created from two data frames in R

  16. 16

    Описание моего типа Parser как серии преобразователей монад

  17. 17

    Как изменить цвета запятых и скобок в VS Code

  18. 18

    Сброс значения <input type = "time"> в Firefox

  19. 19

    Почему прокси в vue.config.js 404

  20. 20

    Как установить параметр -noverify с gradle ktx для робоэлектрических тестов Android?

  21. 21

    В чем разница между ifstream, ofstream и fstream?

популярныйтег

файл