2014-11-10 4 views
2

I 다음 SQL을 가지고SQL 가입 그룹 항목

SELECT articles.id, articles.title, tags.name AS tags 
FROM articles 
LEFT JOIN article_tag_association ON articles.id = article_tag_association.article_id 
LEFT JOIN tags ON tags.id = article_tag_association.tag_id 

가 제한

예컨대 놨어요 물품이 갖는 각 태그에 대한 행을 생성 제외이 OK 작동

[ 
"0" => ["id" => "1", "title" => "test", "tags" => "tag1"], 
"1" => ["id" => "1", "title" => "test", "tags" => "tag2"], 
"2" => ["id" => "2", "title" => "test2", "tags" => "tag1"], 
] 

(만 2 개 기사하지만 세 행)

는 태그의 배열과 각 기사를 반환 할 수있는 방법이있다? 같은

뭔가 :

[ 
"0" => ["id" => "1", "title" => "test", "tags" => ["tag1", "tag2"]], 
"1" => ["id" => "2", "title" => "test2", "tags" => ["tag1"]], 
] 
+0

당신은 당신의 테이블 창조를 게시 할 수 있냐? 문자열 형식의 "배열"을 생성하는 것이 더 쉬울 수도 있습니다 –

답변

3

기본적으로 배열을 반환 할 수 없습니다. 문자열을 장식/연결하여 문자열과 같은 배열을 생성 할 수 있습니다. 좋은 생각이라면? 당신의 상황에 달려 있습니다. 경우,

SELECT 
    concat(
    '[', 
    concat('ID => "', articles.id,'"'), 
    concat('Title => "', articles.title,'"'), 
    concat('Tags => [', GROUP_CONCAT(concat('"',tags.name, '"')), ']'), 
    ']' 
    ) as Array_String 
FROM 
    articles 
     LEFT JOIN 
    article_tag_association ON articles.id = article_tag_association.article_id 
     LEFT JOIN 
    tags ON tags.id = article_tag_association.tag_id 
GROUP BY articles.id 

이 배열로 당신에게 각 행을 줄 것이다 : 또한 MySQL은 당신이 시도 할 수 있습니다 테스트 목적을 위해 어쨌든 몇 가지 제한 GROUP_CONCAT을 위해 (1024 개 * 문자를 반환합니다)

을 가지고 유의하시기 바랍니다 한 줄에 모든 것을 group_concat 아래에두기를 원한다.

참고 : 결과보다 큰 1024 문자 인 경우

SET group_concat_max_len = 1000000; >> size of your string length 

PS를 사용해야합니다 : 위의 코드를 테스트하지 않았습니다. 그것을 테스트해라 :)

1
SELECT articles.id, articles.title, GROUP_CONCAT(tags.name) AS tags 
FROM articles 
LEFT JOIN article_tag_association ON articles.id = article_tag_association.article_id 
LEFT JOIN tags ON tags.id = article_tag_association.tag_id 
GROUP BY articles.id 

당신은 MySQL의에서 배열을 반환 할 수는 없지만이 연결된 문자열을 얻을 PHP 측의 배열로 분할 할 수 있습니다. '접착제'에 사용되는 문자는 GROUP_CONCAT(name SEPARATOR '#')으로 선택하여 이름에 표시하면 안되므로 배열로 분리해도 안전합니다.

+0

"배열"을 반환하지는 않지만 태그에 연결된 문자열은 ... –

+1

@ RaphaëlAlthaus SQL에는 배열 개념이 없습니다. –

+0

mysql에서 배열을 반환 할 수는 없지만이 연결 문자열을 가져 와서 PHP 쪽 – David162795