选择具有相应值的不同列名称

时间:2012-03-11 10:44:27

标签: mysql sql

我有桌子

P_Id | userid | year | month | day
-----+--------+------+-------+------
 3   |      3 | 2011 |     2 |    2
 5   |      1 | 2011 |     2 |    3
16   |      8 | 2011 |     3 |    4
 5   |      3 | 2011 |     4 |    4
17   |     1  | 2011 |     4 |    6
 8   |      4 | 2011 |     7 |    7
 9   |      3 | 2011 |     8 |    8
10   |      8 | 2011 |     9 |    9

我想选择不同的列,即userid,但也要选择首先遇到的年月和年的相应值。

对于上面给出的表,应该输出

P_Id | userid | year | month | day
-----+--------+------+-------+------
   3 |      3 | 2011 |     2 |    2
   5 |      1 | 2011 |     2 |    3
  16 |      8 | 2011 |     3 |    4
   8 |      4 | 2011 |     7 |    7

或 如果我按年,月和日订购餐桌 必须首先选择首先遇到的用户ID,并且不能选择休息

3 个答案:

答案 0 :(得分:1)

将年,月和日放入原生日期列,然后执行以下操作:

select p_id, userid, min(the_date) from table group by p_id, userid

它将提供最快的结果。

如果您无法修改表格并且应使用年+月+日,那么您可以将此值转换为日期并仍使用 min 功能。

答案 1 :(得分:1)

SELECT ta.*
FROM
    ( SELECT DISTINCT userid
      FROM tableX
    ) AS di
  JOIN
    tableX AS ta
      ON ta.P_id = 
         ( SELECT ti.P_id
           FROM tableX AS ti
           WHERE ti.userid = di.userid
           ORDER BY ti.year, ti.month, ti.day
           LIMIT 1
         )

答案 2 :(得分:1)

您的查询如下;

select * from (select min(p_id)p_id,userid, min(year)year,min(month)month,min(day)day from tsil group by userid) t order by p_id;

这是测试;

create table tsil(p_id int, userid int, year int, month int, day int);
insert into tsil values (3,3,2011,2,2)
                                ,(5,1,2011,2,3)
                                ,(16,8,2011,3,4)
                                ,(5,3,2011,4,4)
                                ,(17,1,2011,4,6)
                                ,(8,4,2011,7,7)
                                ,(9,3,2011,8,8)
                                ,(10,8,2011,9,9);
commit;
select * from (select max(p_id)p_id,userid, min(year)year,min(month)month,min(day)day from tsil group by userid) t order by p_id;
drop table tsil;

这是结果;你的期望。

+------+--------+------+-------+------+
| p_id | userid | year | month | day  |
+------+--------+------+-------+------+
|    3 |      3 | 2011 |     2 |    2 |
|    5 |      1 | 2011 |     2 |    3 |
|    8 |      4 | 2011 |     7 |    7 |
|   16 |      8 | 2011 |     3 |    4 |
+------+--------+------+-------+------+