表一:product
字段如下:
id      product_id      product_time(上市时间)
1       1               2007-12-01
2       2               2007-11-01
3       3               2007-10-01
4       4               2007-09-01
5       5               2007-08-01
6       6               2007-07-01表二:dig_product 
字段如下:
id      product_id    addtime(添加评论时间)
1       1             2007-05-17
2       1             2007-05-17
3       1             2007-05-17
4       3             2007-05-17
5       3             2007-05-17
6       4             2007-05-17
7       5             2007-05-17这两个表的含义是:product表是一个产品表,dig_product是关于产品的评论表,把每天评论的机型存放到这个表中。也就是说每个产品在这个表中有多条纪录,比如:在2007-05-17这一天里,product_id等于1的产品被评论了3次,在这个表的体现形式就是存在3条product_id等于1的,addtime等于2007-05-17的纪录。现在查询的要求是:
两个表联合查询,把所有机型取出来做个排序,按照评论数最多,上市时间最新的来排序。
比如:把每个产品按照评论的次数的多少来排序,比如有1个10次的,5个9次的,那么就是10次的排在最前面,5个9次的再按照上市时间这样来排,没有被评论的产品就是评论次数为0次,也一次按照上市时间来排序。下面看看我写的:
SELECT p.*,count( d.product_id ) AS total
FROM product p left join dig_product d on p.product_id = d.product_id  group by d.product_id order by total desc,p.product_time desc这样在排序方面能够做到先按照评论次数来排序,然后再按照上市时间来排序,但是现在有一个问题是:检索出来的纪录数目有问题。dig_product表中有多少条纪录,就只能检索出多少条纪录来。
这不符合我的要求,我的要求是把所有产品都检索出来,没有被评论的就是0次,按照上市时间来排序。请大家帮忙想想办法,在线等待

解决方案 »

  1.   

    SELECT p.*,count( d.product_id ) AS total
    FROM product p left join dig_product d on p.product_id = d.product_id  group by d.product_id order by total desc,p.product_time desc
    Union 
    Select id,product_id,product_time,0  as total
      From product 
        Where  not exist
             ( Select product_id 
                   From dig_product 
                        Where product.product_id = dig_prodcut.product_id) 
                   order by product_time desc
             )
      

  2.   

    Select id,product_id,product_time,0  as total请问一下这里的0  as total是什么意思?
      

  3.   

    就是total这个列里的值都是0,就是你要求的没有被评论过的产品吧 ?
      

  4.   

    兄弟,想别的办法,比如你把所有不为零的都选出来了,你只要union 在product   中有而在dig--中没有的把 count 设为零就行了啊
      

  5.   


    select p.* ,count(d.product_id) as c
    from product as p left join dig_product as d on p.product_id=d.product_id
    group by p.product_id
    order by c desc,p.product_time楼主 你要显示全部商品当然 group by p.product.id了啊