简体   繁体   中英

Get the record by the lowest ID

I have a table:

table name: page_description
desciption_id (pk), page_id (fk), language_id (fk), name
1,                  1,            1,                First page
2,                  1,            2,                First page_second_lang
3,                  2,            1,                Second page
4,                  3,            2,                Third page

Generaly this table contains datas from pages on different languages.

The first row means: First page name is 'First Page' at language 1 - whitch is english right now.

I want every page from the page table, and the name at the LOWEST language_id!

So something like this:
1, 1, 1, First page
3, 2, 1, Second Page
4, 3, 2, Third page

I have a query for it:

SELECT * 
FROM heading_description 
GROUP BY heading_id 
ORDER BY heading_id ASC, 
         language_id ASC

It gives back what I want. But if the table looks like this:

table name: page_description
desciption_id, page_id, language_id, name
1,             1,       2,           First page_second_lang
2,             1,       1,           First page
3,             2,       1,           Second page
4,             3,       2,           Third page

ORDER BY wont give back what I want. I tried.

Here: http://sqlfiddle.com/#!2/de7bd/6/0

In the first row I want to see language_id 1.

I assume page_id and language_id are the primary key

Something like this works ( sql fiddle )

select pd.* 
  from page_description pd 
  join (select page_id, 
               min(language_id) as language_id
          from page_description 
         group by page_id) as a
    using (page_id, language_id);

I'm guessing that your table's primary key is heading_id. If that's the case, you shouldn't be grouping on it (it's always unique) or ordering by it either:

SELECT * 
FROM heading_description 
ORDER BY language_id ASC

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