0

我目前的查询。我可以将它们组合成更少以获得相同的结果吗?我正在尝试将有关线索的特定信息放入名为 $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];
4

3 回答 3

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'

然后使用这个派生的“源”字段来确定哪些值属于哪里。

于 2013-01-22T18:42:50.330 回答
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' 
于 2013-01-22T18:44:26.187 回答
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' )
于 2013-01-22T18:42:31.327 回答