phpmyadmin 从元键列获取2个 meta值

q3aa0525  于 2022-11-09  发布在  PHP
关注(0)|答案(2)|浏览(107)

我需要使用一些库来导出产品名称,SKU和价格到一个CSV文件。这个库使用PDO连接,需要一个SQL查询。
我想选择'名称','SKU'和'价格'从2 WordPress表,即wp_posts和wp_postmeta。
我不知道如何从“ meta_value”列中获取两次数据,例如“meta_key”=“_price”和“meta_key”=“_sku”。

我的当前查询:

"SELECT a.post_title, m1.meta_value, m2.meta_value FROM wp_posts a, wp_postmeta m1, wp_postmeta m2
        WHERE a.post_type='product' AND m1.post_id = a.ID
        AND m1.meta_key='_sku'
        AND m2.meta_key='_price'"
kpbwa7wx

kpbwa7wx1#

这听起来像是你可以做一个连接,这样你就可以把 meta信息与正确的帖子联系起来。

SELECT
  post.post_title,
  meta.meta_value
FROM wp_posts AS post
LEFT JOIN wp_postmeta AS meta
  ON post.post_id = meta.post_id
WHERE post.post_type = 'product'
  AND meta.meta_key IN ('_sku', '_price')

示例结果:

post_title    | meta_value
--------------|-----------
Cheddar       | CHE001
Cheddar       | 2.45
Red Leicester | CHE002
...

这假定wp_posts中的id列是post_id
需要注意的是,这将为每个帖子返回最多两行,这取决于它是否有_sku_price的 meta行)。如果您需要所有数据都在同一行上(就像导出时一样),您可能需要这样的代码:

SELECT
  post.post_title,
  metaSku.meta_value AS sku,
  metaPrice.meta_value AS price
FROM wp_posts AS post
LEFT JOIN (
  SELECT
    *
  FROM wp_postmeta
  WHERE meta_key = '_sku'
) AS metaSku
  ON post.post_id = metaSku.post_id
LEFT JOIN (
  SELECT
    *
  FROM wp_postmeta
  WHERE meta_key = '_price'
) AS metaPrice
  ON post.post_id = metaPrice.post_id
WHERE post.post_type = 'product'

示例结果:

post_title    | sku    | price
--------------|--------|------
Cheddar       | CHE001 | 2.45
Red Leicester | CHE002 |
...

我希望这能帮上忙。

knsnq2tg

knsnq2tg2#

这会对我有用

SELECT post.post_title, metaSku.meta_value AS sku, metaPrice.meta_value AS price FROM wp_posts AS post LEFT JOIN ( SELECT * FROM wp_postmeta WHERE meta_key = '_sku' ) AS metaSku ON post.ID = metaSku.post_id LEFT JOIN ( SELECT * FROM wp_postmeta WHERE meta_key = '_price' ) AS metaPrice ON post.ID = metaPrice.post_id WHERE post.post_type = 'product';

相关问题