带有子查询和联接的MySQL UPDATE

时间:2018-12-21 17:15:46

标签: mysql database

嗨,我是子查询的新手,所以不确定我做对了吗

我对此很满意

SELECT t2.cons, t1.date, t1.account_no  FROM
(
SELECT date, account_no FROM  tbl_consignment_x3
) t1
INNER JOIN
(
SELECT cons, date, account_no FROM
tbl_volume_analysis 
) t2
ON t2.account_no=t1.account_no AND t2.date=t1.date 

它给了我想要使用的结果

所以我希望下面这样的事情可以做我想要的,但是我不能正确使用语法,而且我不确定我的技术是否完全错误

UPDATE tbl_margin_all t3 
(
SELECT t2.cons, t1.date, t1.account_no  FROM
(
SELECT date, account_no FROM  tbl_consignment_x3
) t1
INNER JOIN
(
SELECT cons, date, account_no FROM
tbl_volume_analysis 
) t2
ON t2.account_no=t1.account_no AND t2.date=t1.date 
)
SET t3.cons=t2.cons 
WHERE t1.date=t3.date AND t1.account_no=t3.account_no

谢谢

添加: 首先,我对从发货单中提取的特定日期的发货总数进行总计数,然后将其与日期和帐户一起写在体积表中。然后从发货单中,我要写入我所做的每个发货中的计数。

2 个答案:

答案 0 :(得分:0)

您需要加入第一个子查询-将JOIN放在t3之后。

实际上,您根本不需要任何子查询,只需直接与表连接即可。

UPDATE tbl_margin_all AS t3
JOIN tbl_consignment_x3 AS t1 ON t1.date = t3.date AND t1.account_no=t3.account_no
JOIN tbl_volume_analysis AS t2 ON t2.account_no=t1.account_no AND t2.date=t1.date 
SET t3.cons = t2.cons

SELECT查询中,它应该是:

SELECT t2.cons, t1.date, t1.account_no  
FROM tbl_consignment_x3 AS t1
JOIN tbl_volume_analysis AS t2
ON t2.account_no=t1.account_no AND t2.date=t1.date 

答案 1 :(得分:0)

请注意t3之后的逗号

UPDATE tbl_margin_all_4000 t3,
(
    SELECT cons, t1.date, t1.account_no FROM
    (
        SELECT date, account_no, consignment_no FROM tbl_consignment_x3_4000
    ) t1
    INNER JOIN
    (
        SELECT cons, date, account_no FROM
        tbl_volume_analysis_4000 
    ) t2
    ON t2.account_no=t1.account_no AND t2.date=t1.date 
) as src
SET t3.cons=src.cons
WHERE t3.date=src.date AND t3.account_no=src.account_no

此查询花费了4分钟。我已经按照建议的方式尝试了两次联接,但这花了45分钟。