根据具有条件的另一个表更新表

时间:2017-05-26 15:02:21

标签: mysql sql join

我想更新post_type = productpost_status = publish的所有列。此外,我需要进行连接,因为我只想更新那些帖子,Count(...)也是0。

我想计算元meta_key LIKE "%product_shops_%_price%"

以下是表格的两个例子:

wp441_posts:

| ID | post_status | post_type |
--------------------------------
|  1 |   publish   |  product  |
|  2 |    darf     |  product  |
|  3 |    darf     |  product  |
|  4 |   publish   |    page   |
|  5 |   publish   |    page   |
|  6 |   publish   |    page   |
--------------------------------

wp441_postmeta:

| meta_id | post_id |        meta_key         | met_value |
----------------------------------------------------------
|  1      |    1    |  product_shops_0_price  |    45.00  
|  2      |    1    |  product_shops_1_price  |    25.00  |
|  3      |    1    |  product_shops_2_price  |    45.00  |
|  4      |    2    |       thumbnail_url     | https://..|
-----------------------------------------------------------

例如。在这两个表中,我只想将post_status 1的ID设置为draft,因为这是我的条件匹配的唯一帖子。我在wp441_postmeta表中有超过0 product_shops_%_price的价格,我现在有一个帖子在publish,它是一个'product``。

我已经修改了一个声明但是这个声明现在没有加入:

SELECT COUNT(meta_key) FROM `wp441_postmeta` WHERE meta_key LIKE "%product_shops_%_price%" GROUP BY (post_id) 

现在我需要在此语句中插入连接。但我不知道怎么样......有人可以帮我吗?

问候!

1 个答案:

答案 0 :(得分:0)

对于您解释的案例,请将wp441_posts.post_status更新为值draft,其中:

  • post_type = 'product AND post_status = 'public'
  • 并将post_idwp441_postmeta.post_id匹配,其中meta_key LIKE '%product_shops_%_price%'
  • 的行数超过1行

声明如下:

UPDATE wp441_posts p
JOIN (
  SELECT pm.post_id
  FROM wp441_postmeta
  WHERE meta_key LIKE '%product_shops_%_price%'
  GROUP BY pm.post_id
  HAVING COUNT(*) > 0
  ) pm
  ON p.id = pm.post_id
SET post_status = 'draft'
WHERE pm.post_type = 'product' AND pm.post_status = 'publish'

我认为您的LIKE应与product_shops_%_price进行比较,而不会在字符串的开头和结尾处添加%符号,但这与WordPress如何将值放在那里有关。考虑一下。