Programing

여러 MySQL 행을 하나의 필드로 연결할 수 있습니까?

lottogame 2020. 9. 27. 12:37
반응형

여러 MySQL 행을 하나의 필드로 연결할 수 있습니까?


를 사용하여 MySQL다음과 같이 할 수 있습니다.

SELECT hobbies FROM peoples_hobbies WHERE person_id = 5;

내 출력 :

shopping
fishing
coding

하지만 대신 1 행, 1 열을 원합니다.

예상 출력 :

shopping, fishing, coding

그 이유는 여러 테이블에서 여러 값을 선택하고 모든 조인 후에 원하는 것보다 많은 행을 갖게되기 때문입니다.

MySQL Doc 에서 함수를 찾았 는데 CONCAT또는 CONCAT_WS함수가 결과 집합을 받아들이는 것처럼 보이지 않습니다. 여기있는 사람이이 작업을 수행하는 방법을 알고 있습니까?


다음을 사용할 수 있습니다 GROUP_CONCAT.

SELECT person_id, GROUP_CONCAT(hobbies SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

Ludwig가 주석 에서 언급했듯이 DISTINCT중복을 피하기 위해 연산자를 추가 할 수 있습니다 .

SELECT person_id, GROUP_CONCAT(DISTINCT hobbies SEPARATOR ', ')
FROM peoples_hobbies 
GROUP BY person_id;

Jan 이 의견 에서 언급했듯이 다음을 사용하여 파열하기 전에 값을 정렬 할 수도 있습니다 ORDER BY.

SELECT person_id, GROUP_CONCAT(hobbies ORDER BY hobbies ASC SEPARATOR ', ')
FROM peoples_hobbies
GROUP BY person_id;

Dag의 의견 에서 언급했듯이 결과에는 1024 바이트 제한이 있습니다. 이 문제를 해결하려면 쿼리 전에 다음 쿼리를 실행하십시오.

SET group_concat_max_len = 2048;

물론 2048필요에 따라 변경할 수 있습니다 . 값을 계산하고 할당하려면 :

SET group_concat_max_len = CAST(
    (SELECT SUM(LENGTH(hobbies)) + COUNT(*) * LENGTH(', ')
    FROM peoples_hobbies 
    GROUP BY person_id)
    AS UNSIGNED
);

GROUP_CONCATMySQL 버전 (4.1)이 지원하는지 살펴보십시오 . 자세한 내용 은 설명서 를 참조하십시오.

다음과 같이 보일 것입니다.

  SELECT GROUP_CONCAT(hobbies SEPARATOR ', ') 
  FROM peoples_hobbies 
  WHERE person_id = 5 
  GROUP BY 'all';

여러 개별 행 을 연결 하는 대체 구문

경고 :이 게시물은 당신을 배고프 게 만들 것입니다.

주어진:

그룹 대신 개별 행을 여러 개 선택 하고 특정 필드에 연결 하고 싶었습니다 .

제품 ID와 이름 및 가격 테이블이 있다고 가정 해 보겠습니다.

+------------+--------------------+-------+
| product_id | name               | price |
+------------+--------------------+-------+
|         13 | Double Double      |     5 |
|         14 | Neapolitan Shake   |     2 |
|         15 | Animal Style Fries |     3 |
|         16 | Root Beer          |     2 |
|         17 | Lame T-Shirt       |    15 |
+------------+--------------------+-------+

그런 다음이 강아지를 확인란으로 나열하는 멋진 슈만시 아약스가 있습니다.

Your hungry-hippo user selects 13, 15, 16. No dessert for her today...

Find:

A way to summarize your user's order in one line, with pure mysql.

Solution:

Use GROUP_CONCAT with the the IN clause:

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary FROM product WHERE product_id IN (13, 15, 16);

Which outputs:

+------------------------------------------------+
| order_summary                                  |
+------------------------------------------------+
| Double Double + Animal Style Fries + Root Beer |
+------------------------------------------------+

Bonus Solution:

If you want the total price too, toss in SUM():

mysql> SELECT GROUP_CONCAT(name SEPARATOR ' + ') AS order_summary, SUM(price) AS total FROM product WHERE product_id IN (13, 15, 16);
+------------------------------------------------+-------+
| order_summary                                  | total |
+------------------------------------------------+-------+
| Double Double + Animal Style Fries + Root Beer |    10 |
+------------------------------------------------+-------+

PS: Apologies if you don't have an In-N-Out nearby...


You can change the max length of the GROUP_CONCAT value by setting the group_concat_max_len parameter.

See details in the MySQL documantation.


There's a GROUP Aggregate function, GROUP_CONCAT.


In my case I had a row of Ids, and it was neccessary to cast it to char, otherwise, the result was encoded into binary format :

SELECT CAST(GROUP_CONCAT(field SEPARATOR ',') AS CHAR) FROM table

Use MySQL(5.6.13) session variable and assignment operator like the following

SELECT @logmsg := CONCAT_ws(',',@logmsg,items) FROM temp_SplitFields a;

then you can get

test1,test11

I had a more complicated query, and found that I had to use GROUP_CONCAT in an outer query to get it to work:

Original Query:

SELECT DISTINCT userID 
FROM event GROUP BY userID 
HAVING count(distinct(cohort))=2);

Imploded:

SELECT GROUP_CONCAT(sub.userID SEPARATOR ', ') 
FROM (SELECT DISTINCT userID FROM event 
GROUP BY userID HAVING count(distinct(cohort))=2) as sub;

Hope this might help someone.


Try this:

DECLARE @Hobbies NVARCHAR(200) = ' '

SELECT @Hobbies = @Hobbies + hobbies + ',' FROM peoples_hobbies WHERE person_id = 5;

For somebody looking here how to use GROUP_CONCAT with subquery - posting this example

SELECT i.*,
(SELECT GROUP_CONCAT(userid) FROM favourites f WHERE f.itemid = i.id) AS idlist
FROM items i
WHERE i.id = $someid

So GROUP_CONCAT must be used inside the subquery, not wrapping it.


we have two way to concatenate columns in MySql

select concat(hobbies) as `Hobbies` from people_hobbies where 1

Or

select group_concat(hobbies) as `Hobbies` from people_hobbies where 1

참고URL : https://stackoverflow.com/questions/276927/can-i-concatenate-multiple-mysql-rows-into-one-field

반응형