1. 程式人生 > 其它 >join行轉列,union列轉行

join行轉列,union列轉行

技術標籤:mysqlmysqlsql

1、join行轉列

成績表grades1,新增資料

CREATE TABLE `grades1` (
  `id` int(4) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(20) DEFAULT NULL COMMENT '姓名',
  `subject` varchar(20) DEFAULT NULL COMMENT '學科',
  `score` int(4) DEFAULT NULL COMMENT '成績',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB
AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; INSERT INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (1, 'lyy', '英語', 100); INSERT INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (2, 'lyy', '數學', 98); INSERT INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (3, 'lyy', '語文', 97); INSERT
INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (4, 'gss', '英語', 89); INSERT INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (5, 'gss', '數學', 88); INSERT INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (6, 'gss', '語文', 87); INSERT INTO `grades1`(`id`, `name`, `subject`, `score`
) VALUES (7, 'liming', '英語', 79); INSERT INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (8, 'liming', '數學', 77); INSERT INTO `grades1`(`id`, `name`, `subject`, `score`) VALUES (9, 'liming', '語文', 75);

表grades1原資料

表資料

查詢sql

-- 1.使用 join on 查詢
SELECT yw.name,yw.score '語文',sx.score '數學',yy.score '英語'
FROM
(SELECT NAME,score FROM grades1 WHERE SUBJECT='語文') yw JOIN
(SELECT NAME,score FROM grades1 WHERE SUBJECT='數學') sx JOIN
(SELECT NAME,score FROM grades1 WHERE SUBJECT='英語') yy
ON yw.name=sx.name AND sx.name=yy.name

-- 2.使用 join using 查詢
SELECT yw.name,yw.score '語文',sx.score '數學',yy.score '英語'
FROM
(SELECT NAME,score FROM grades1 WHERE SUBJECT='語文') yw JOIN
(SELECT NAME,score FROM grades1 WHERE SUBJECT='數學') sx USING(NAME) JOIN
(SELECT NAME,score FROM grades1 WHERE SUBJECT='英語') yy USING(NAME)

查詢結果


注意:以上join連線語句使用了join buffer緩衝區進行查詢,可以使用執行計劃EXPLAIN進行檢視
join buffer

2、union列轉行

成績表grades2,新增資料

CREATE TABLE `grades2` (
  `id` int(4) NOT NULL AUTO_INCREMENT COMMENT 'id',
  `name` varchar(20) DEFAULT NULL COMMENT '姓名',
  `語文` int(4) DEFAULT NULL COMMENT '語文',
  `數學` int(4) DEFAULT NULL COMMENT '數學',
  `英語` int(4) DEFAULT NULL COMMENT '英語',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

INSERT INTO `grades2`(`id`, `name`, `語文`, `數學`, `英語`) VALUES (1, 'lyy', 88, 89, 87);
INSERT INTO `grades2`(`id`, `name`, `語文`, `數學`, `英語`) VALUES (2, 'gss', 93, 92, 91);
INSERT INTO `grades2`(`id`, `name`, `語文`, `數學`, `英語`) VALUES (3, 'liu', 99, 88, 77);

表grades2原資料

查詢sql

SELECT NAME,'語文' SUBJECT,語文 score FROM grades2  -- '語文',該列為自加列subject;語文,該列為成績score
UNION ALL
SELECT NAME,'數學' SUBJECT,數學 score FROM grades2
UNION ALL
SELECT NAME,'英語' SUBJECT,英語 score FROM grades2

注意:union與union all的區別:union在表關聯的時候會自動進行去重操作,union all關聯所有資料(包含重複);
在沒有去重需求時,建議使用union all,效率較高

查詢結果