使用带有union的select查询的MySQL Update表使每个派生表必须有自己的别名错误

时间:2017-05-04 14:11:45

标签: mysql sql

我遇到了一个查询问题,该问题使我能够将多个表中的产品详细信息移动到单个表中。这是我的开始查询

UPDATE tbl_temp_color_pricing cp ,
(SELECT
SKU ,
pkID ,
pkSKU ,
pkBrand ,
pkCategory ,
pkClass ,
pkSuperCategory
FROM
(
    (
    SELECT
    sb.SKU ,
    pb.pkID ,
    sb.pkID AS pkSKU ,
    pb.pkBrand ,
    pb.pkCategory ,
    cat.pkClass ,
    cat.pkSuperCategory
    FROM SKU_Basic AS sb
    JOIN ProductBase AS pb ON(sb.pkProduct = pb.pkID)
    JOIN Categories AS cat ON(pb.pkCategory = cat.pkID)
    )
    UNION ALL
        (SELECT
                p.SKU ,
                p.pkID ,
                p.pkSKU ,
                p.p.pkBrand ,
                p.pkCategory ,
                p.pkClass ,
                p.pkSuperCategory
            FROM
                tbl_products AS p
            WHERE
                p.storeID = 2)

)) skuMatch
SET cp.matchSKU = skuMatch.SKU ,
 cp.pkID = skuMatch.pkID ,
 cp.pkSKU = skuMatch.pkSKU ,
 cp.pkBrand = skuMatch.pkBrand,
 cp.pkCategory = skuMatch.pkCategory ,
 cp.pkClass = skuMatch.pkClass ,
 cp.pkSuperCat = skuMatch.pkSuperCategory
WHERE cp.storeID = 2 AND cp.adminID = 7

所以我根据迄今为止找到的答案为查询添加别名:

...
    FROM SKU_Basic AS sb
    JOIN ProductBase AS pb ON(sb.pkProduct = pb.pkID)
    JOIN Categories AS cat ON(pb.pkCategory = cat.pkID)
    ) t1
    UNION ALL
        (...
            FROM
                tbl_products AS p
            WHERE
                p.storeID = 2) t2

)) skuMatch

现在我得到了

  

错误:您的SQL语法出错;检查手册   对应于您的MySQL服务器版本,以便使用正确的语法   靠近't2

)) skuMatch
SET cp.matchSKU = skuMatch.SKU ,
 cp.pkID = skuMatch.pkID ,
 ' at line 37

我在这里做错了什么?

1 个答案:

答案 0 :(得分:0)

我在此问题的研究中发现的每个先前的答案都表明我需要在两个子查询中添加别名,但事实并非如此。从第二个子查询中删除别名,如下所示:

UPDATE tbl_temp_color_pricing cp , (SELECT SKU, pkID, pkSKU, pkBrand, pkCategory, pkClass, pkSuperCategory FROM
    (
        SELECT sb.SKU, pb.pkID, sb.pkID AS pkSKU, pb.pkBrand, pb.pkCategory, cat.pkClass, cat.pkSuperCategory FROM SKU_Basic AS sb JOIN ProductBase AS pb ON(sb.pkProduct = pb.pkID) JOIN Categories AS cat ON(pb.pkCategory = cat.pkID)
    ) AS originalData <-- this alias is required
    UNION ALL
    (
        SELECT p.SKU, p.pkID, p.pkSKU, p.pkBrand, p.pkCategory, p.pkClass, p.pkSuperCategory FROM tbl_products AS p WHERE p.storeID = 2
    ) <-- no alias required
) AS skuMatch
SET cp.matchSKU = skuMatch.SKU,  cp.pkID = skuMatch.pkID,  cp.pkSKU = skuMatch.pkSKU,  cp.pkBrand = skuMatch.pkBrand,  cp.pkCategory = skuMatch.pkCategory,  cp.pkClass = skuMatch.pkClass,  cp.pkSuperCat = skuMatch.pkSuperCategory
WHERE cp.storeID = 2 AND cp.adminID = 7

使查询能够无错误地运行。

希望能帮助其他人遇到这个问题。