简体   繁体   中英

distinct value which has maximum id

I am facing a problem in mysql query,i have 2 table.

  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 

I want to access title from table news_info distinct value which has maximum pid

I am using following query

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

it give me distinct value but not max id. it give min id value.

This will give you the answer to the question that you asked. I'm not sure if it's what you actually want though.

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

Here is another approach:

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

In your example, there are no duplicate pids, so there is only one with the maximum value.

Here is yet another approach:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM