如何将 MySQL 数据合并为一个 table

How to combine MySQL data into one table

我有 3 个 table。

  1. A users table with just an id and a name.
  2. A students table with id, name and subject.
  3. A students_enrolled table which is now empty.

我想从 'users' table 中找到在 'students' table 中具有匹配项的所有 table 条目。为此,我有以下查询:

SELECT  *
FROM    students
WHERE   name  IN (SELECT name FROM users);

QUERY RESULTS:

id  name
3   mark
4   steve

This works but now the GOAL is to pupulate the third table ('students_enrolled') with this data and have the ids match the users table. In the users table 'mark' is ID 3 and 'steve' is ID 4, but in the students table they are IDs 50 and 99 respectively. I want to insert them into the 'students_enrolled' table with matches IDs to the users table. Note: the 'names' will always be unique - there will never be two steves within one table.

The goal is to have the 'students_enrolled' table show this:

id  name    status  subject
3   mark    enrolled    math
4   steve   enrolled    reading

如果有人在这里有任何想法,我已经创建了一个包含所有架构和数据的 sqlfiddle:

[sql fiddle link 到架构和数据:http://sqlfiddle.com/#!9/c5ea5/1][1]

Schema:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;

INSERT INTO `users` (`id`, `name`)
VALUES
    (1, 'john'),
    (2, 'jane'),
    (3, 'mark'),
    (4, 'steve');

-- ----------------

CREATE TABLE `students` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(25) DEFAULT NULL,
  `subject` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;


INSERT INTO `students` (`id`, `name`, `subject`)
VALUES
    (50, 'mark', 'math'),
    (99, 'steve', 'reading');


-- ----------------

CREATE TABLE `students_enrolled` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  `status` varchar(255) DEFAULT NULL,
  `subject` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=5 DEFAULT CHARSET=latin1;


/* Desired result:*/
/* INSERT INTO `students_enrolled` (`id`, `name`, `status`, `subject`)
VALUES
    (3, 'mark', 'enrolled', 'math'),
    (4, 'steve', 'enrolled', 'reading'); */

-- ----------------

Thanks for the help!

您可以使用 INSERT ... SELECT 语句进行插入:

INSERT INTO `students_enrolled` (`id`, `name`, `status`, `subject`)
SELECT u.`id`, s.`name`, 'enrolled', s.`subject`
FROM `students` AS s
INNER JOIN `users` AS u ON s.`name` = u.`name`

您可以在 users.id 字段使用 INNER JOIN

Demo here

编辑:

您可以使用 NOT EXISTS:

过滤掉 students_enrolled table 中已有的记录
INSERT INTO `students_enrolled` (`id`, `name`, `status`, `subject`)
SELECT u.`id`, s.`name`, 'enrolled', s.`subject`
FROM `students` AS s
INNER JOIN `users` AS u ON s.`name` = u.`name`
WHERE NOT EXISTS (SELECT 1 
                  FROM `students_enrolled` AS se
                  WHERE se.`id` = u.`id`);