简体   繁体   中英

How to fix an SQL query which has a specifying table twice error

I have this query:

SELECT *
FROM `wp_postmeta`
WHERE `meta_key` = '_test'
  AND `post_id` IN (SELECT post_id FROM `wp_postmeta`
                    where meta_value = 8023)

Returns the SQL error:

Table 'wp_postmeta' is specified twice, both as a target for 'UPDATE' and as a separate source for data

I have read other answers and attempting to add a further SELECT * FROM ( ) around the sub query but didn't help.

I assume I need some form of AS in here but can't figure out the exact code.

Can you rewrite the query in the format that won't trigger the error?

The same for this similar query:

UPDATE wp_postmeta
SET meta_value = 5.55
WHERE meta_key = '_regular_price'
AND post_id IN (
    SELECT post_id
    FROM wp_postmeta
    WHERE meta_value = 8023
)`

You can use alias for table name
(and as suggestion in your case you can also use join instead of in )

  SELECT a.*
  FROM `wp_postmeta` a
  inner join  `wp_postmeta` b on  a.`post_id = b.post_id 
  where a.`meta_key` = '_test'
  and b.meta_value = 8023

In update you could use a join with subselect for circumvent the limits due to update actions on the same table

  UPDATE wp_postmeta a
  inner join (
    SELECT post_id
    FROM wp_postmeta
    WHERE meta_value = 8023
  ) t on  a.`post_id = t.post_id and a.`meta_key` = '_test'
  SET meta_value = 5.55
SELECT * FROM wp_postmeta  as wp_out 
WHERE wp_out.meta_key = '_test' 
          AND wp_out.post_id IN 
              ( SELECT wp_in.post_id 
                FROM wp_postmeta  as wp_in 
                where wp_in.meta_value = 8023)

尽管这不是一个好的答案,但是它是有效的,哈哈wp_postmeta * FROM wp_postmeta WHERE meta_key =' wp_postmeta meta_key post_id IN(SELECT GROUP_CONCAT(post_id)FROM wp_postmeta其中meta_value = 8023)

The SELECT query posted in the question is equivalent to this one:

SELECT p1.*
FROM `wp_postmeta` p1
  INNER JOIN `wp_postmeta` p2 ON p1.`post_id` = p2.`post_id`
WHERE p1.`meta_key` = '_test'
  AND p2.`meta_value` = 8023

In fact, if some conditions are met, the MySQL engine converts the original SELECT query into a query similar to this as an optimization .

This SELECT query can be easily changed into the desired UPDATE query:

UPDATE `wp_postmeta` p1
  INNER JOIN `wp_postmeta` p2 ON p1.`post_id` = p2.`post_id`
SET p1.`meta_values` = 5.55
WHERE p1.`meta_key` = '_test'
  AND p2.`meta_value` = 8023

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM