通过查询将值从一个表插入另一个表

时间:2012-12-14 07:51:34

标签: mysql sql

我有两张表,如下面

CREATE TABLE projectlist(ProjectId   INT NOT NULL PRIMARY KEY,
                         ProjectName VARCHAR(50),
                         Location    VARCHAR(50));

CREATE TABLE LocationList(LocaId INT NOT NULL PRIMARY KEY AUTO_INCREMENT,
                          ProjectId INT,
                          Location    VARCHAR(50));

表中的值如下

INSERT INTO projectlist(ProjectId, ProjectName)
                 VALUES(1, 'Project A'),
                       (2, 'Project B'),
                       (3, 'Project C'),
                       (4, 'Project D'),
                       (5, 'Project E'),
                       (6, 'Project F'),
                       (7, 'Project G'),
                       (8, 'Project H');

INSERT INTO LocationList(ProjectId, Location)
                  VALUES(1, 'Location A'),
                        (1, 'Location C'),
                        (2, 'Location C'),
                        (2, 'Location B'),
                        (2, 'Location A'),
                        (3, 'Location B'),
                        (4, 'Location C'),
                        (5, 'Location D'),
                        (6, 'Location A'),
                        (6, 'Location B'),
                        (7, 'Location B'),
                        (8, 'Location D'),
                        (8, 'Location A');

我想要一个插入查询,将第一个 LocationList.Location 插入到 projectlist.Location 中,用于与项目ID相关的各个项目。

运行查询后的表项目列表是

   ProjectName                 Location
    Project A                 Location A 
    Project B                 Location C
    Project C                 Location B
    Project D                 Location C
    Project E                 Location D
    Project F                 Location A
    Project G                 Location B
    Project H                 Location D    

我尝试了一个SQL查询,它带来了LocationList表中的First Location,如下所示。

 SELECT DISTINCT MNPCL.Location, MNP.ProjectId
   FROM LocationList MNPCL RIGHT OUTER JOIN
        projectlist MNP ON MNP.ProjectId = MNPCL.ProjectId                            
  GROUP BY MNP.ProjectName

如何编写在项目列表中执行插入的查询位置

感谢回复

3 个答案:

答案 0 :(得分:1)

这是SQLFiddle demo

update projectlist 
join 
(
select LocationList.ProjectID,LocationList.Location 
  from LocationList
join 
(select LocationList.ProjectID,min(LocaId) minLocaId 
    from LocationList 
    group by LocationList.ProjectID) l1
        on LocationList.LocaId=l1.minLocaID
 ) l2 on projectList.ProjectID=l2.ProjectID
SET ProjectList.Location=l2.Location

答案 1 :(得分:1)

尝试:

UPDATE projectlist AS prj SET Location = 
(SELECT Location FROM LocationList AS lst WHERE lst.ProjectId = prjProjectId ORDER BY Location DESC LIMIT 1)

由于您的项目在LocationList中有多个位置,并且您只能在项目列表表中有一个位置,因此必须将结果集限制为一行。

答案 2 :(得分:0)

这对你有用......

UPDATE projectlist AS prj SET Location = (
SELECT group_concat(locationlist.Location SEPARATOR ',') as loc FROM `locationlist` left join projectlist using (ProjectId) 
group by locationlist.ProjectId)