嗨我需要使用另一张表中的count来订购。我找到了这个很好的例子,我使用它作为我需要的查询的模型。 SQL - How To Order Using Count From Another Table
我用于查询的模型是:
SELECT bloggers.*, COUNT(post_id) AS post_count
FROM bloggers LEFT JOIN blogger_posts
ON bloggers.blogger_id = blogger_posts.blogger_id
GROUP BY bloggers.blogger_id
ORDER BY post_count
但我有一个语法问题,我想,我试图用另一个表替换下一个查询...但我无法设法做到这一点。原始查询:
$res3=$db->execute_query("select id,scode,sname from ".TABLE_PREFIX."states where ccode=? order by sname asc",array($country));
尝试替换此查询..
$res3=$db->execute_query("select ".TABLE_PREFIX."states.* , COUNT(".TABLE_PREFIX."items.state) AS state_count FROM ".TABLE_PREFIX."states LEFT JOIN ".TABLE_PREFIX."items ON ".TABLE_PREFIX."states.id = ".TABLE_PREFIX."items.state GROUP BY ".TABLE_PREFIX."states.id ORDER BY state_count DESC",array($country));
答案 0 :(得分:1)
试试这个:
$res3=$db->execute_query("select a.* , COUNT(b.state) AS state_count FROM states a
LEFT JOIN items b ON a.id = b.state
GROUP BY a.id
ORDER BY state_count DESC",array($country));