-2

我有 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,依此类推。

4

2 回答 2

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
于 2012-05-17T08:38:14.213 回答
0

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

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 
于 2012-05-17T08:24:59.287 回答