MySQL의 여러 열을 기반으로 행을 열로 동적 변환
이전 질문에서는 MySQL 쿼리를 사용하여 행을 동적으로 변환했습니다. 단일 열의 열에. 이제 "data"와 "price"라는 두 열에 대해 동일한 결과를 달성하는 것을 목표로 합니다.
문제:
다음 표의 데이터를 열로 변환합니다. "order1", "order2", "order3", "item1", "item2", "item3" 및 "item4"라는 이름이 지정되었습니다. "주문" 및 "항목" 열.
id | order | data | item | Price |
---|---|---|---|---|
1 | 1 | P | 1 | 50 |
1 | 1 | P | 2 | 60 |
1 | 1 | P | 3 | 70 |
1 | 2 | Q | 1 | 50 |
1 | 2 | Q | 2 | 60 |
1 | 2 | Q | 3 | 70 |
2 | 1 | P | 1 | 50 |
2 | 1 | P | 2 | 60 |
2 | 1 | P | 4 | 80 |
2 | 3 | S | 1 | 50 |
2 | 3 | S | 2 | 60 |
2 | 3 | S | 4 | 80 |
원하는 결과:
id | order1 | order2 | order3 | item1 | item2 | item3 | item4 |
---|---|---|---|---|---|---|---|
1 | P | Q | 50 | 60 | 70 | ||
2 | P | S | 50 | 60 | 80 |
해결책:
"주문" 및 "항목" 값의 수가 다음과 같은 경우 하드 코딩된 쿼리를 사용할 수 있습니다. 알려져 있지만 일반적인 경우에는 보다 동적인 솔루션이 필요합니다.
데이터 피벗 해제:
MySQL에는 피벗 해제 기능이 없지만 UNION ALL을 사용하여 변환할 수 있습니다. 여러 데이터 쌍을 행으로 변환:
select id, concat('order', `order`) col, data value from tableA union all select id, concat('item', item) col, price value from tableA;
값을 다시 열:
CASE:
select id, max(case when col = 'order1' then value end) order1, max(case when col = 'order2' then value end) order2, max(case when col = 'order3' then value end) order3, max(case when col = 'item1' then value end) item1, max(case when col = 'item2' then value end) item2, max(case when col = 'item3' then value end) item3 from ( select id, concat('order', `order`) col, data value from tableA union all select id, concat('item', item) col, price value from tableA ) d group by id;
동적 준비 문:
이 포함된 집계 함수를 사용하여 피벗되지 않은 데이터를 다시 열로 변환할 수 있습니다.마지막으로 집합 기반 연결 및 실행:
SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'max(case when col = ''', col, ''' then value end) as `', col, '`') ) INTO @sql FROM ( select concat('order', `order`) col from tableA union all select concat('item', `item`) col from tableA )d; SET @sql = CONCAT('SELECT id, ', @sql, ' from ( select id, concat(''order'', `order`) col, data value from tableA union all select id, concat(''item'', item) col, price value from tableA ) d group by id'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt;
이 접근 방식은 MySQL의 여러 기준에 따라 행을 열로 변환하는 유연하고 동적인 방법을 제공합니다.
위 내용은 여러 열을 기반으로 MySQL에서 행을 열로 동적으로 변환하는 방법은 무엇입니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

mysqlviewshavelimitations : 1) 그들은 upportallsqloperations, datamanipulation throughviewswithjoinsorbqueries를 제한하지 않습니다

적절한 usermanagementInmysqliscrucialforenhancingsecurityandensuringfefficientDatabaseOperation.1) USECREATEUSERTOWDDUSERS,@'localHost'or@'%'.

mysqldoes notimposeahardlimitontriggers, butpracticalfactorsdeteirefectiveuse : 1) ServerConfigurationimpactStriggerManagement; 2) 복잡한 트리거 스케일 스케일 사이드로드; 3) argertableSlowtriggerTriggerPerformance; 4) High ConconcercencyCancaUspriggerContention; 5) m

예, It 'safetostoreBlobdatainmysql, butconsidertheStefactors : 1) StoragesPace : BlobScanconSumeSignificantspace, 잠재적으로 증가하는 CostsandSlownperformance

PHP 웹 인터페이스를 통해 MySQL 사용자를 추가하면 MySQLI 확장 기능을 사용할 수 있습니다. 단계는 다음과 같습니다. 1. MySQL 데이터베이스에 연결하고 MySQLI 확장자를 사용하십시오. 2. 사용자를 생성하고 CreateUser 문을 사용하고 Password () 함수를 사용하여 암호를 암호화하십시오. 3. SQL 주입 방지 및 MySQLI_REAL_ESCAPE_STRING () 함수를 사용하여 사용자 입력을 처리하십시오. 4. 새 사용자에게 권한을 할당하고 보조금 명세서를 사용하십시오.

mysql'sblobissuilableforstoringbinarydatawithinareldatabase, whilenosqloptionslikemongodb, redis, and cassandraofferflexible, scalablesolutionsforunstuctureddata.blobissimplerbutcanslowwownperformance를 사용하는 것들보업 betterscal randaysand

TOADDAUSERINMYSQL, 사용 : CreateUser'UserName '@'host'IdentifiedBy'Password '; 여기서'showTodoitseciRely : 1) ChoosetheHostCareLyTocon trolaccess.2) setResourcelimitswithOptionslikemax_queries_per_hour.3) Usestrong, iriquepasswords.4) enforcessl/tlsconnectionswith

toavoidcommonmistakeswithstringdatatypesinmysql, stroundStringTypenuances, chooseTherightType, andManageEncodingAndCollationSettingSefectively.1) usecharforfixed-lengthstrings, varcharvariable-length, andtext/blobforlargerdata.2) setcarcatter


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

MinGW - Windows용 미니멀리스트 GNU
이 프로젝트는 osdn.net/projects/mingw로 마이그레이션되는 중입니다. 계속해서 그곳에서 우리를 팔로우할 수 있습니다. MinGW: GCC(GNU Compiler Collection)의 기본 Windows 포트로, 기본 Windows 애플리케이션을 구축하기 위한 무료 배포 가능 가져오기 라이브러리 및 헤더 파일로 C99 기능을 지원하는 MSVC 런타임에 대한 확장이 포함되어 있습니다. 모든 MinGW 소프트웨어는 64비트 Windows 플랫폼에서 실행될 수 있습니다.

안전한 시험 브라우저
안전한 시험 브라우저는 온라인 시험을 안전하게 치르기 위한 보안 브라우저 환경입니다. 이 소프트웨어는 모든 컴퓨터를 안전한 워크스테이션으로 바꿔줍니다. 이는 모든 유틸리티에 대한 액세스를 제어하고 학생들이 승인되지 않은 리소스를 사용하는 것을 방지합니다.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

Dreamweaver Mac版
시각적 웹 개발 도구

에디트플러스 중국어 크랙 버전
작은 크기, 구문 강조, 코드 프롬프트 기능을 지원하지 않음