以最低ID获取记录

时间:2012-12-29 21:36:32

标签: mysql group-by record min

我有一张桌子:

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 

我有一个查询:

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

它回馈了我想要的东西。但如果表格如下:

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不会回馈我想要的东西。我试过了。

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

在第一行中我想看到language_id 1。

2 个答案:

答案 0 :(得分:1)

我假设page_id和language_id是主键

这样的事情有效(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);

答案 1 :(得分:0)

我猜你的表的主键是heading_id。如果是这种情况,你不应该对它进行分组(它总是唯一的)或者由它排序:

SELECT * 
FROM heading_description 
ORDER BY language_id ASC