1

我有两张桌子,如下所示

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');

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

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

   项目名称 位置
    项目 A 地点 A
    项目 B 地点 C
    项目 C 地点 B
    项目 D 地点 C
    项目 E 位置 D
    项目 F 地点 A
    项目 G 地点 B
    项目 H 地点 D    

我尝试了一个 SQL 查询,它从 LocationList 表中获取第一个位置,如下所示。

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

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

谢谢您的回复

4

3 回答 3

1

这是一个SQLFiddle 演示

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
于 2012-12-14T08:16:44.527 回答
1

尝试:

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

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

于 2012-12-14T08:30:02.710 回答
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)
于 2012-12-14T09:17:12.990 回答