PHP / SQL,减少查询次数

时间:2016-05-12 16:57:16

标签: php mysql

我在php中查询一个大型数据库,而且我的表现并不好。 我有我需要的代码,我简单找不到压缩这些语句的好方法。

    $q = $_GET['q'];
    (dbinit)
    $query = "SELECT post_id FROM wp_postmeta WHERE meta_key = '_billing_email' AND meta_value = '$q'";
    $result = mysql_query($query);

    while ($row = mysql_fetch_array($result))
{
$thing = $row['post_id'];
$querys = "SELECT 'meta_value' FROM wp_postmeta WHERE post_id = '$thing' AND meta_key = '_order_number'";
$results = mysql_query($querys);
$rows = mysql_fetch_array($results);
$postid = $rows['meta_value'];
$queryss = "SELECT post_id FROM $table WHERE meta_value = $postid AND meta_key = '_order_number'";
$resultss = mysql_query($query);
$rowss = mysql_fetch_array($result);
$order_id = $rowss['post_id'];
(handling)
}

我想知道是否有更有效的方法来执行这些查询,或者是否可以在一个查询中使用它们?

1 个答案:

答案 0 :(得分:0)

不确定$table的来源。

但这个JOIN尝试应该有效:

$q = $_GET['q'];
// ... dbinit ...

$query = "SELECT wpp.post_id,
       wpp1.meta_value as orderNumber,
       wpp2.post_id as orderId

    FROM wp_postmeta wpp
    LEFT JOIN wp_postmeta wpp1 
    ON wpp1.post_id = wpp.post_id 
      AND wpp1.meta_key = '_order_number'
    LEFT JOIN $table wpp2
    ON  wpp2.meta_value = wpp1.meta_value 
      AND wpp2.meta_key = '_order_number'
    WHERE wpp.meta_key = '_billing_email' 
      AND meta_value = '$q'";

$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
    (handling)
}

如你所见,你可以得到

$thing = $row['post_id'];
$order_id = $row['orderId'];
如果需要,

在循环内部。