在sql中显示具有相同id的一行中的值

时间:2017-02-14 10:59:10

标签: mysql

我有三个表,我加入表并检索此查询中的所有值

sql查询:

 SELECT wp_term_relationships.object_id, wp_posts.post_title,                                        
 wp_postmeta.meta_key, wp_postmeta.meta_value
 FROM `wp_posts` , wp_postmeta, wp_term_relationships
 WHERE (wp_posts.ID = wp_postmeta.post_id)
 AND (wp_postmeta.post_id = wp_term_relationships.object_id)  
 AND wp_term_relationships.term_taxonomy_id =33

它的显示表结构是这个

object_id     post_title          meta_key           meta_value
 302       CHICKEN CHOW MEIN     post_image           url1
 302        CHICKEN CHOW MEIN      price              6.95

我希望在一个中显示OBject Id,并将我想要的一行中的两行合并为

object_id     post_title      meta_value(price)     meta_value(post_image)
302       CHICKEN CHOW MEIN         6.95                url1

3 个答案:

答案 0 :(得分:0)

您可以使用更常用的连接语法

加入wp_postmeta两次
SELECT rel.object_id, p.post_title,
       meta_price.meta_key, meta_price.meta_value,
       meta_image.meta_key, meta_image.meta_value
FROM `wp_posts` p
    inner join wp_postmeta meta_price on meta_price.post_id = p.ID
    inner join wp_postmeta meta_image on meta_image.post_id = p.ID
    inner join wp_term_relationships rel on rel.objet_id = p.ID
WHERE rel.term_taxonomy_id = 33
    and meta_price.meta_key = 'price'
    and meta_image.meta_key = 'post_image'

(语法未选中 - 此处无法访问WordPress数据库 - 您需要稍微更改所选列。)

答案 1 :(得分:0)

如果是我,我只需坚持使用您现有的查询,并在应用程序代码中处理数据透视,所以。

*PHP goes here*

$query = "

 SELECT r.object_id
      , p.post_title
      , m.meta_key
      , m.meta_value
   FROM wp_posts p
   JOIN wp_postmeta m
     ON m.post_id = p.ID 
   JOIN wp_term_relationships r
     ON r.object_id = m.post_id
  WHERE r.term_taxonomy_id = 33
  ORDER 
     BY post_title
      , meta_key;

";

*More PHP goes here*

答案 2 :(得分:-1)

语法未选中,但是这样的话?

for $value in distinct-values(
  doc('database/dataset.xml')/dataset/body/instances/instance/value[5]
)
return <value>{$value}</value>