编辑JOIN查询,以便具有唯一值的字段

时间:2009-05-06 00:57:46

标签: mysql

我有一个JOIN查询,用于提取最后6个“主题”记录(topic_status为0的最高topic_id记录,即不是垃圾邮件):

SELECT topic_title, topic_slug, meta_value, topic_poster
FROM `folio_topics` as Topics
INNER JOIN `folio_topicmeta` as Topicmeta
ON Topics.topic_id = Topicmeta.topic_id
WHERE `topic_status` = 0
AND Topicmeta.meta_key = 'bb_attach_thumb'
ORDER BY Topics.`topic_id` DESC
LIMIT 6

我想编辑这个查询,以便folio_topics.topic_poster字段是唯一的,即所以我不会获得具有相同topic_poster的6条记录,而是6条记录,所有记录都具有唯一的topic_poster值。

任何帮助将不胜感激! : - )


重复文森特的回答,我提出了一个查询,正确地为每个topic_poster提取最高 topic_id,但需要8.7秒,这与大多数查询相比非常慢(超过0.1秒)。有没有办法优化这个查询?

SELECT topic_title, topic_slug, meta_value, topic_poster
FROM `folio_topics` AS Topics
INNER JOIN `folio_topicmeta` AS Topicmeta
ON Topics.topic_id = Topicmeta.topic_id
WHERE Topics.topic_id IN (
    SELECT MAX(`topic_id`)
    FROM `folio_topics`
    WHERE `topic_status` = 0
    GROUP BY `topic_poster`)
AND Topicmeta.meta_key = 'bb_attach_thumb'
ORDER BY Topics.`topic_id` DESC
LIMIT 6

2 个答案:

答案 0 :(得分:1)

根据this文章,您可以使用Group By来完成您正在尝试的内容。试试这个

SELECT topic_title, topic_slug, meta_value, topic_poster
FROM `folio_topics` as Topics
INNER JOIN `folio_topicmeta` as Topicmeta
ON Topics.topic_id = Topicmeta.topic_id
WHERE `topic_status` = 0
AND Topicmeta.meta_key = 'bb_attach_thumb'
Group By topic_poster
ORDER BY Topics.`topic_id` DESC
LIMIT 6

答案 1 :(得分:0)

如果遇到任何人,我找不到一种方法来快速运行这个巨大的查询,所以我将它分成两个代码查询。这是PHP代码:

$folio_posters = $wpdb->get_results("SELECT MAX( `topic_id` ) as topiclist FROM `folio_topics` WHERE `topic_status` =0 GROUP BY `topic_poster` ORDER BY topiclist DESC LIMIT 6");

foreach ($folio_posters as $folio_poster) {
    $folio_poster_list[] = $folio_poster->topiclist;
}

$foliopics = $wpdb->get_results("SELECT topic_title, topic_slug, meta_value, topic_poster FROM `folio_topics` AS Topics INNER JOIN `folio_topicmeta` AS Topicmeta ON Topics.topic_id = Topicmeta.topic_id WHERE Topics.topic_id IN (" .  implode ($folio_poster_list, ',') . ") AND Topicmeta.meta_key = 'bb_attach_thumb' ORDER BY Topics.`topic_id` DESC");

如果有人想出如何用一个查询来做,我会接受那个版本。 : - )