具有最大id的不同值

时间:2013-03-23 12:28:45

标签: mysql sql distinct max

我在mysql查询中遇到问题,我有2个表。

  1. category_info

    cid cname
    1   Latest News
    2   Notice Board
    3   Headline
    
  2. news_info

    pid cid title               date
    1   1   mobile              2013-03-04
    2   1   fish                2013-03-04
    3   2   Airtel india        2013-03-04
    4   2   Marco Simoncelli    2013-03-05
    5   3   title1              2013-03-22
    6   1   title               2013-03-22
    7   3   International Opportunity   2013-03-22
    
  3. 我想从表格news_info访问具有最大pid

    的不同值的标题

    我正在使用以下查询

    SELECT a.*, b.*  FROM category_info AS a RIGHT JOIN news_info AS b ON (a.cid = b.cid)  GROUP BY a.cid
    

    它给了我明显的价值但不是最大ID。它给出了最小的id值。

3 个答案:

答案 0 :(得分:1)

这将为您提供您提出的问题的答案。我不确定这是不是你真正想要的。

select distinct title
from news_info
where pid = 
(select max(pid) from news_info)

答案 1 :(得分:0)

这是另一种方法:

select ni.*
from news_info ni
order by pid desc
limit 1

在您的示例中,没有重复的pid,因此只有一个具有最大值。

答案 2 :(得分:0)

这是另一种方法:

SELECT *
FROM news_info n
LEFT JOIN category_info c ON a.cid = b.cid
--
-- the maximum pid := there should not exist a higher pid value (for the same cid)
--
WHERE NOT EXISTS (
   SELECT * FROM news_info x
   WHERE x.cid = n.cid
   AND x.pid > n.pid
    );
相关问题