使用select from和多个连接的SQL更新表

时间:2013-07-06 07:16:40

标签: mysql sql join phpmyadmin sql-update

以下是我的表格的相关栏目

  • bia_panelsid, sign_id, value, project_id

  • bia_clientsid, name

  • bia_projectsid, name, client_id, city_id

  • bia_citiesid, name

我正在尝试将bia_panels.project_id更新为bia_projects.id bia_panels.value = bia_clients.namepanels.project_id =000,其中值不是空白当然我必须使用多个连接来获取有

    -- UPDATE
SELECT * FROM
`bia_panels` AS t1
    JOIN  bia_clients AS t2 
        ON t1.value = t2.name 
    JOIN bia_projects AS  t3 
        ON t2.id = t3.client_id 


-- SET t1.project_id = t3.id

-- WHERE t1.value<>'' AND t1.project_id = '000' 
WHERE t1.value <>''

问题是这不能给我正确的结果(我的项目ID在连接中的某处不正确,会返回多个结果,因此它们会中断

我知道,一旦我能够正确选择部分,我就可以使用更新

例如,可能有多个面板,其中value=client.name但不是所有面板都是相同的项目ID

2 个答案:

答案 0 :(得分:0)

  

和bia_panels.ID = bia_panels.project_id

您的选择查询中缺少加入条件,应该添加

 JOIN bia_projects ON bia_clients.id = bia_projects.client_id  and bia_panels.ID = bia_panels.project_id

以下查询应该给出正确的输出

SELECT  sign_id, value, left(sign_id, 3) AS city_ID  ,  
bia_clients.id AS 'client id',  bia_projects.id AS proj_id , bia_cities.id
FROM bia_panels
 JOIN  bia_clients ON bia_panels.value = bia_clients.name 
 JOIN bia_projects ON bia_clients.id = bia_projects.client_id  and bia_panels.ID = bia_panels.project_id
JOIN bia_cities ON bia_projects.city_id = bia_cities.id WHERE bia_panels.value<>'' AND bia_panels.project_id = '000' ORDER BY value

答案 1 :(得分:0)

我会将您的查询重新组织为UPDATE查询:

UPDATE bia_panels p, bia_clients c, bia_projects t
  SET p.project_id=t.id
  WHERE p.value=c.name
    AND t.client_id=c.id
    AND p.project_id=''