如何只选择一行?

时间:2012-05-17 08:14:54

标签: php mysql sql sql-server

我有2张桌子

   NAME
   +----+---------+
   | id |   name  |
   +----+---------+
   |  1 |   ABC   |
   |  2 |   CCC   |
   +----+---------+

   TBL_STATUS
   +----+-----------+--------+
   | id |  name_id  | status |
   +----+-----------+--------+
   |  1 |     1     |   KU   |
   |  2 |     1     |   HP   |
   |  3 |     1     |   HK   |
   |  4 |     2     |   KU   |
   |  5 |     2     |   HP   |
   +----+-----------+--------+

我选择并加入(INNER JOIN)这两张桌子。 这是我查询的结果。

   +---------+--------+
   |   name  | status |
   +---------+--------+
   |   ABC   |   HK   |
   |   ABC   |   HP   |
   |   ABC   |   KU   |
   |   CCC   |   HP   |
   |   CCC   |   KU   |
   +---------+--------+

每个名称可以有3个状态。 HK,HP或KU。 对于最新状态,我只想为每个名称添加一行。 例如:

   +---------+--------+
   |   name  | status |
   +---------+--------+
   |   ABC   |   HK   |
   |   CCC   |   HP   |
   +---------+--------+

状态优先级应首先显示HK(如果有), 然后,如果没有HK显示HP,等等..

2 个答案:

答案 0 :(得分:1)

您的最终输出

正在正确的轨道上
   +----+---------+--------+
   | id |   name  | status |
   +----+---------+--------+
   |  1 |   ABC   |   HK   | -- Need to remove
   |  2 |   ABC   |   HP   | -- Need to remove
   |  3 |   ABC   |   KU   |
   |  5 |   CCC   |   HP   | -- Need to remove
   |  6 |   CCC   |   KU   | 
   +----+---------+--------+

您只需要将其限制为每个名称的最大ID,这可以通过聚合查询中的INNER JOIN在下面实现。

SELECT  Name, Status
FROM    Name
        INNER JOIN tbl_Status
            ON tbl_Status.Name_ID = Name.ID
        INNER JOIN
        (   SELECT  MAX(ID) AS MaxStatusID
            FROM    Tbl_Status
            GROUP BY Name_ID
        ) MaxStatus
            ON MaxStatusID = tbl_Status.ID

答案 1 :(得分:0)

您必须从TBL_STATUS找到max(id),然后将所有数据连接在一起,例如:

SELECT n.name, st3.status 
FROM name AS n 
LEFT JOIN 
  (SELECT st1.name_id, MAX(st1.id) AS max_id
     FROM TBL_STATUS st1 
     GROUP BY name_id) AS st2
  ON n.id=st2.name_id
LEFT JOIN 
  TBL_STATUS st3
  ON st2.max_id = st3.id