mysqli:根据一些参数在1中合并行

fhg3lkii  于 2021-06-18  发布在  Mysql
关注(0)|答案(3)|浏览(309)

我有一个mysql表,在那里我有相同的文本,但在不同的语言

ID, Lang, Text, number, chapter

 1, English, Hello, 2, 1

 4, German, Hallo, 2, 1

 5, Spanish, Hola, 2, 1

你怎么能看到这些

Select * from table where chapter=1  (and language: english,german,spanish)

ID, lang1, lang2, lang3, number, chapter

 5, Hello, Hallo, Hola, 2, 1

我想在一行中连接列

zysjyyx4

zysjyyx41#

您可以尝试使用条件聚合函数来实现它。
架构(mysql v5.7)

CREATE TABLE T(
  ID int,
  Lang varchar(50),
  Text varchar(50),
  number int,
  chapter int
);

INSERT INTO T VALUES (1, 'English', 'Hello', 2, 1);
INSERT INTO T VALUES (4, 'German',  'Hallo', 2, 1);
INSERT INTO T VALUES (5, 'Spanish', 'Hola', 2, 1);

查询#1

SELECT MAX(ID) id,
       MAX(CASE WHEN Lang ='English' THEN Text END) lang1,
       MAX(CASE WHEN Lang ='German' THEN Text END) lang2,
       MAX(CASE WHEN Lang ='Spanish' THEN Text END) lang3,
       number, 
       chapter  
FROM T
GROUP BY number, chapter;

| id  | lang1 | lang2 | lang3 | number | chapter |
| --- | ----- | ----- | ----- | ------ | ------- |
| 5   | Hello | Hallo | Hola  | 2      | 1       |

db fiddle视图

e1xvtsh3

e1xvtsh32#

创建表测试:

CREATE TABLE test (
                id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
                Lang VARCHAR(30) NOT NULL,
                Text VARCHAR(30) NOT NULL,
                number VARCHAR(50),
                chapter INT(10))

插入记录:

insert into test values(1,'English','Hello','2',1);
insert into test values(4,'German','Hallo','2',1);     
insert into test values(5,'Spanish','Hola','2',1); 

+----+---------+-------+--------+---------+
| id | Lang    | Text  | number | chapter |
+----+---------+-------+--------+---------+
|  1 | English | Hello | 2      |       1 |
|  4 | German  | Hallo | 2      |       1 |
|  5 | Spanish | Hola  | 2      |       1 |
+----+---------+-------+--------+---------+

SELECT MAX(id) id, MAX(CASE WHEN Lang ='English' THEN Text END) lang1, 
    MAX(CASE WHEN Lang ='German' THEN Text END) lang2, 
    MAX(CASE WHEN Lang ='Spanish' THEN Text END) lang3, number, chapter 
    FROM test GROUP BY number, chapter;

+------+-------+-------+-------+--------+---------+
| id   | lang1 | lang2 | lang3 | number | chapter |
+------+-------+-------+-------+--------+---------+
|    5 | Hello | Hallo | Hola  | 2      |       1 |
+------+-------+-------+-------+--------+---------+
bzzcjhmw

bzzcjhmw3#

SELECT * FROM
(SELECT LangAS t1, vargu FROM table LANG=114 AND chapter=1) as A,
(SELECT LangAS t2 FROM table WHERE LANG=115 AND chapter=1) AS B,
(SELECT LangAS t3 FROM table  WHERE LANG=116 AND chapter=1) AS C;

相关问题