有两个库(bbs、cms),三张表
bbs库的表bbs_users里面存在一些带字段test的用户,表结构如下:
username(用户名称) test
cms库 里面有两张表,分别为cms_posts,cms_users
cms_posts表结构大体如下:
ID(文章ID,后面提取文章要用到) post_author(发表该文章的用户ID)cms_users结构如下:
ID(用户ID) user_login(用户名称)现在想查询bbs_users库里面带字段test的所有用户,然后根据这些用户去查询cms_posts里面的最新文章ID,选最新的一篇文章。我写了个语句如下:
先取出bbs_users里面的所有带字段test的用户,如下:
$sql1 = "SELECT username,test FROM bbs.bbs_users where test = 1";
$clubs = $wpdb->get_results($sql1);
foreach($clubs as $club){
$name = $club->user_name;$sql = "select * from (SELECT a.*,b.user_login,b.ID as user_id FROM cms_posts a LEFT OUTER JOIN cms_users b ON a.post_author = b.ID WHERE b.user_login = '$name' and post_status IN ('publish','static') group by ID order by post_date_gmt DESC limit 1 ) as total group by user_id order by post_date_gmt limit 10";
$POSTS = $wpdb->get_results($sql);
foreach ( $POSTS as $post ) {
$uid2 = $post->user_id;
$username = get_userdata($uid2);
        $output = "用户名:".$username->user_login."<br>文章名称:".get_permalink($post->ID).";
       }
        echo $output;
}输出的内容却达不到我要的效果,如用户会出现两次,最新文章输出也不对,求高人指点。。

解决方案 »

  1.   

    求高人指点,如下:use bbs;create table bbs_users
    (
    username varchar(20)
    vip int(1)
    )use cms;
    create table cms_posts
    (
    ID bigint(20)    [文章ID]
    post_author int(20)
    post_date_gmt datetime
    )create table cms_users
    (
    ID bigint(20)    [用户ID]
    user_login varchar(20)
    )
    查询bbs_users中vip字段等于1的用户,然后根据这个用户的user_name去查询cms_users中的用户ID,再根据这个用户ID去查询cms_posts中相关的文章,输出10个用户的最新文章。想查询的结果如下:username ID[文章ID] post_date_gmt
    张三      123       2012-06-03 12:50:28
    李四      234       2012-06-02 12:50:27
    赵六      234       2012-06-01 12:50:27