0

我目前正在尝试计算在特定价格范围内有多少房产,而我正在运行的查询仅返回 1 的值。显然我做错了什么——而且不那么精通 MySQL/PhP 也无济于事..有人介意帮忙吗?

查询如下:

    $apart = $wpdb->get_var("SELECT m1.post_id
    FROM hj_postmeta m1
    INNER JOIN hj_postmeta m2 ON m1.post_id = m2.post_id
    WHERE m1.meta_key = 'price'
    AND m1.meta_value
    BETWEEN 50000 AND 74999 AND m2.meta_key = 'property_type'
    AND m2.meta_value = 'apartment'");

$apartprice = count($apart); 

提前谢谢了。

4

2 回答 2

4

用作函数get_resultsget_var 数据库返回单个变量

$apart = $wpdb->get_results("SELECT m1.post_id
    FROM hj_postmeta m1
    INNER JOIN hj_postmeta m2 ON m1.post_id = m2.post_id
    WHERE m1.meta_key = 'price'
    AND m1.meta_value
    BETWEEN 50000 AND 74999 AND m2.meta_key = 'property_type'
    AND m2.meta_value = 'apartment'");

$apartprice = count($apart); 

或全部计数get_var

$apart = $wpdb->get_var("SELECT COUNT(m1.post_id)
    FROM hj_postmeta m1
    INNER JOIN hj_postmeta m2 ON m1.post_id = m2.post_id
    WHERE m1.meta_key = 'price'
    AND m1.meta_value
    BETWEEN 50000 AND 74999 AND m2.meta_key = 'property_type'
    AND m2.meta_value = 'apartment'");

$apartprice = $apart;
于 2012-09-23T19:30:40.150 回答
1

只要您直接对行数感兴趣:

$apart = $wpdb->get_var("....");
$apartprice = $wpdb->num_rows;

但是,我认为Mihai Iorga 的回答提出了两个非常公平的观点,以防您需要获取数据库中的所有数据或(如上面 juergen d 所评论的)计数,如果您实际上并未处理该变量旁边的结果集。

于 2012-09-23T19:36:45.583 回答