有没有更有效的方法来编写这4个MYSQL查询以使用更少的查询?

时间:2013-01-22 18:39:27

标签: php mysql performance

我目前的疑问。我可以将它们组合成更少以获得相同的结果吗?我正在尝试将有关该路径的特定信息获取到名为$ trail。

的数组中
$result = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_city' ");
$result = mysql_fetch_array($result);
$trail[city] = $result[0];

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

$result = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'location_state' ");
$result = mysql_fetch_array($result);
$trail[state] = $result[0];

$result = mysql_query("SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND `meta_key` = 'difficulty' ");
$result = mysql_fetch_array($result);
$trail[difficulty] = $result[0];

$result = mysql_query("SELECT guid FROM wp_posts WHERE `post_parent` = $id AND `post_type` = 'attachment' ");
$result = mysql_fetch_array($result);
$trail[image] = $result[0];

3 个答案:

答案 0 :(得分:2)

这适用于meta_values:

SELECT meta_value, meta_key
...
WHERE (post_id = $id) AND (meta_key IN ('location_city', 'length', ...)

guid查询可能会更好地作为单独的查询运行。如果你坚持减少一个查询调用,那么联盟就可以

SELECT 'meta' AS source, meta_value, meta_key
WHERE ...

UNION ALL

SELECT 'guid' AS source, guid, null
FROM ...
WHERE post_parent = $id and post_type = 'attachment'

然后使用这个派生的'source'字段来确定哪个值属于哪里。

答案 1 :(得分:1)

如果您想要列中的数据,那么您可以JOIN查询:

SELECT lc.meta_value Location_City,
    l.meta_value Location,
    ls.meta_value LocationState,
    d.meta_value Difficulty,
    p.guid
FROM wp_postmeta lc
LEFT JOIN wp_postmeta l
    on lc.`post_id` = l.`post_id`
    and l.`meta_key` = 'length'
LEFT JOIN wp_postmeta ls
    on lc.`post_id` = ls.`post_id`
    and ls.`meta_key` = 'location_state'
LEFT JOIN wp_postmeta d
    on lc.`post_id` = d.`post_id`
    and d.`meta_key` = 'difficulty'
LEFT JOIN wp_posts p
    on lc.`post_id` = p.`post_parent`
    and p.`post_type` = 'attachment'
WHERE lc.`post_id` = $id 
    AND lc.`meta_key` = 'location_city' 

答案 2 :(得分:0)

SELECT meta_value FROM wp_postmeta WHERE `post_id` = $id AND (`meta_key` = 'difficulty' OR `meta_key` = 'location_state' OR `meta_key` = 'length'  OR `meta_key` = 'location_city' )