MySQL:子查询根据同一列的另一个值获取值

时间:2015-07-24 05:11:34

标签: mysql wordpress join

我正在使用meta_key meta_value向WordPress wp_postmeta table查询最低item_thickness行:

SELECT min(cast(meta_value as unsigned)) FROM wp_postmeta WHERE meta_key='item_thickness'

这很有效。

问题:如何扩展此查询以从具有相同item_thicknesspost_id以及{{1}的行中选择相同的最低meta_key='item_status' }

meta_value='Raw'形成了这些行之间的关系,但我不知道如何在同一个表上进行JOIN或子查询的正确语法

这是我对查询的最新(失败)尝试:

post_id

1 个答案:

答案 0 :(得分:0)

我能够使用WP_Query构建我需要的MySQL,然后编辑它以便选择我想要的值。

工作查询。

$wpdb->get_var( "SELECT min(cast(wp_postmeta.meta_value as unsigned)) FROM wp_postmeta  INNER JOIN wp_posts ON ( wp_posts.ID = wp_postmeta.post_id )  INNER JOIN wp_postmeta AS mt1 ON ( wp_posts.ID = mt1.post_id ) WHERE 1=1  AND ( wp_postmeta.meta_key = 'item_thickness' AND ( mt1.meta_key = 'item_status' AND CAST(mt1.meta_value AS CHAR) = 'raw' )) AND wp_posts.post_type = 'inventory' AND (wp_posts.post_status = 'publish' OR wp_posts.post_status = 'future' OR wp_posts.post_status = 'draft' OR wp_posts.post_status = 'pending' OR wp_posts.post_status = 'private')" );