简体   繁体   中英

Select query to get all data from junction table to one field

I have 2 tables and 1 junction table:

table 1 (Log):      | Id | Title | Date | ...
table 2 (Category): | Id | Title | ...

junction table between table 1 and 2:

LogCategory: | Id | LogId | CategoryId 

now, I want a sql query to get all logs with all categories title in one field, something like this:

LogId, LogTitle, ..., Categories(that contains all category title assigned to this log id) 

can any one help me solve this? thanks

Try this code:

DECLARE @results TABLE
( 
  idLog int,
  LogTitle varchar(20), 
  idCategory int,
  CategoryTitle varchar(20)
)

INSERT INTO @results
SELECT l.idLog, l.LogTitle, c.idCategory, c.CategoryTitle
FROM
  LogCategory lc
  INNER JOIN Log l 
    ON lc.IdLog = l.IdLog
  INNER JOIN Category c
    ON lc.IdCategory = c.IdCategory

SELECT DISTINCT 
    idLog,
    LogTitle,
    STUFF (
        (SELECT ', ' + r1.CategoryTitle
        FROM @results r1
        WHERE r1.idLog = r2.idLog
        ORDER BY r1.idLog
        FOR XML PATH ('')
        ), 1, 2, '')
FROM 
    @results r2

Here you have a simple SQL Fiddle example

I'm sure this query can be written using only one select, but this way it is readable and I can explain what the code does.

The first select takes all Log - Category matches into a table variable.

The second part uses FOR XML to select the category names and return the result in an XML instead of in a table. by using FOR XML PATH ('') and placing a ', ' in the select, all the XML tags are removed from the result. And finally, the STUFF instruction replaces the initial ', ' characters of every row and writes an empty string instead, this way the string formatting is correct.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM