如何使用INNER JOIN和Multiple SELECT更新多个表

时间:2019-01-23 10:49:32

标签: mysql sql

我正在尝试使用内部Join更新2个表,并使用变量的2个结果设置值。我终于成功地将它用于SELECT。 我想更新具有长where子句的表。并设置来自选择查询的结果。

选择“我得到我的结果”就可以了:

SET @DefID = "5289";

SELECT pt1.ID, pt1.post_title, pt1.post_content, mt2.meta_value
FROM wp_posts AS pt1

INNER JOIN wp_postmeta AS mt1
ON ( pt1.ID = mt1.post_id )
INNER JOIN wp_postmeta AS mt2
ON ( pt1.ID = mt2.post_id )
INNER JOIN wp_postmeta AS mt3
ON ( pt1.ID = mt3.post_id )

WHERE 
    pt1.ID != @DefID
AND
    pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND 
    mt1.meta_key = 'tourmaster-tour-date-avail'
AND 
    CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND 
    mt2.meta_key = '_cornerstone_data'
AND 
    mt3.meta_key = 'tourmaster-tour-duration'
AND 
    mt3.meta_value = '10'
AND    
    pt1.post_type = 'tour'
AND 
    pt1.post_status = 'publish'

ORDER BY mt1.meta_value ASC

但不能使用UPDATE

SET @DefID = "myID";
SET @post_content = ( SELECT wp_posts_bak.post_content FROM wp_posts_bak WHERE wp_posts_bak.ID = @DefID );
SET @meta_value = ( SELECT wp_postmeta_bak.meta_value FROM wp_postmeta_bak WHERE wp_postmeta_bak.post_id = @DefID AND wp_postmeta_bak.meta_key = '_cornerstone_data');

UPDATE wp_posts_bak AS pt1, wp_postmeta_bak AS mt0

INNER JOIN wp_postmeta_bak AS mt1 ON pt1.ID = mt1.post_id
INNER JOIN wp_postmeta_bak AS mt2 ON pt1.ID = mt2.post_id
INNER JOIN wp_postmeta_bak AS mt3 ON pt1.ID = mt3.post_id

SET 
    pt1.post_content  = @post_content,
    mt0.meta_value = @meta_value

WHERE
    pt1.ID != @DefID
AND 
    pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND 
    mt1.meta_key = 'tourmaster-tour-date-avail'
AND 
    CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND 
    mt2.meta_key = '_cornerstone_data'
AND 
    mt3.meta_key = 'tourmaster-tour-duration'
AND 
    mt3.meta_value = '10'
AND    
    pt1.post_type = 'tour'
AND 
    pt1.post_status = 'publish'

遇到以下错误:'on子句中的未知列'pt1.ID'。

1 个答案:

答案 0 :(得分:0)

我终于找到了问题的原因。在UPDATE中,我必须删除2个表。

所以解决方法是:

SET @DefID = "5289";
SET @post_content = ( SELECT wp_posts_bak.post_content FROM wp_posts_bak WHERE wp_posts_bak.ID = @DefID );
SET @meta_value = ( SELECT wp_postmeta_bak.meta_value FROM wp_postmeta_bak WHERE wp_postmeta_bak.post_id = @DefID AND wp_postmeta_bak.meta_key = '_cornerstone_data');

UPDATE wp_posts_bak AS pt1

INNER JOIN wp_postmeta_bak AS mt1 ON pt1.ID = mt1.post_id
INNER JOIN wp_postmeta_bak AS mt2 ON pt1.ID = mt2.post_id
INNER JOIN wp_postmeta_bak AS mt3 ON pt1.ID = mt3.post_id

SET 
    pt1.post_content  = @post_content,
    mt2.meta_value = @meta_value

WHERE
    pt1.ID != @DefID
AND 
    pt1.post_title LIKE '%Banda Sea DIVING Cruise with Tidak%'
AND 
    mt1.meta_key = 'tourmaster-tour-date-avail'
AND 
    CAST(mt1.meta_value AS DATE) >= '2019-01-23'
AND 
    mt2.meta_key = '_cornerstone_data'
AND 
    mt3.meta_key = 'tourmaster-tour-duration'
AND 
    mt3.meta_value = '10'
AND    
    pt1.post_type = 'tour'
AND 
    pt1.post_status = 'publish'