使用PHP将多个MYSQL查询合并为一个

时间:2012-11-30 16:48:36

标签: php mysql

我知道此主题已经涵盖过,我已经阅读了stackoverflow提供的十几个链接。没有符合我的需要。

我有4个使用PHP进行类似数据的mysql查询,我想将其降低到一个查询,并可能将结果放入我可以访问的数组中。这是我目前的代码。

 $id = $row[post_id];
    $resulttwo = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'length' ");
    $temptwo = mysql_fetch_array($resulttwo);       
    $length[$id] = $temptwo[0];

    $id = $row[post_id];
    $resultthree = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_city' ");
    $tempthree = mysql_fetch_array($resultthree);
    $trailcity[$id] = $tempthree[0];

    $id = $row[post_id];
    $resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_state' ");
    $tempfour = mysql_fetch_array($resultfour);
    $trailstate[$id] = $tempfour[0];

    $id = $row[post_id];
    unset($tempfour);
    $resultfour = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'difficulty' ");
    $tempfour = mysql_fetch_array($resultfour);
    $difficulty[$id] = $tempfour[0].' difficulty';`

2 个答案:

答案 0 :(得分:5)

这应该有效:

$id = $row[post_id];
$result = mysql_query("SELECT meta_key, meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` IN ('length', 'location_city', 'location_state', 'difficulty')");
$temp = mysql_fetch_assoc($result);

数组$temp将包含meta_key以及您应该能够meta_value调用的$temp[length]。您可以使用print_r($temp);

检查整个数组

您还应该停止使用mysql_函数编写新代码,因为它们being deprecated并使用mysqli_PDO代替。

答案 1 :(得分:0)

这应该足够了,因为你只关心每个查询中的第一行。

SELECT meta_value FROM wp_postmeta WHERE post_id = $id AND meta_key IN ("length", "location_city", "location_state", "difficulty") LIMIT 4;
该死的太迟了! :/