【问题标题】:distinct value which has maximum id具有最大 id 的不同值
【发布时间】:2013-03-23 12:28:44
【问题描述】:

我在 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
    

我想从表 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 值。

【问题讨论】:

  • 能否请您发布您对上述示例的期望输出。还有你为什么要正确加入的任何理由?
  • 亲爱的 Rush,我希望输出是 pid title date 6 title 2013-03-22 4 Marco Simoncelli 2013-03-05 7 International Opportunity 2013-03-22 谢谢

标签: mysql sql distinct max


【解决方案1】:

这将为您提供所提问题的答案。不过,我不确定这是否是您真正想要的。

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

【讨论】:

    【解决方案2】:

    这是另一种方法:

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

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

    【讨论】:

      【解决方案3】:

      这是另一种方法:

      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
          );
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-12-28
        • 1970-01-01
        • 2021-08-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多