Mysql - 从左连接获取多个最后结果

时间:2014-07-17 12:35:49

标签: mysql left-join

对不起我的英语。

我有3张桌子。联系,contact_attribut,contact_value

联系:

-------------------
|id     | name  |
------------------- 
|1      |  bob  |
|2      |  boby |

contact_attribut:

-------------------
|id     | code   |
------------------- 
|1      | email  |
|2      | sex    |

contact_value:

------------------------------------------------------------------------
|id     | contact_id | attribute_id | creation            | value
------------------------------------------------------------------------
|1      | 1          | 1            | 2014-07-17 12:12:49 | bob@bob.com
|2      | 1          | 2            | 2014-07-17 12:12:56 | Male
|3      | 1          | 2            | 2014-07-17 14:15:58 | Female

现在,我正在寻找一个查询,以获取来自一个联系人的所有唯一属性,但是最后一个唯一属性。找到我的结果查询的方法看起来:

------------------------------------------
|name |contact_id | attribut_id | value
------------------------------------------
|Bob  |1          | 1           | bob@bob.com
|Bob  |1          | 2           | female

我尝试了这个查询:

SELECT * FROM contact AS c
LEFT JOIN contact_value as v ON c.id = v.contact_id
WHERE c.id = '1'
  AND v.creation IN 
  (SELECT MAX(v2.creation) FROM contact_value AS v2 GROUP BY v2.attribute_id)

但结果是:

------------------------------------------
|name |contact_id | attribut_id | value
------------------------------------------
|Bob  |1          | 1           | bob@bob.com
|Bob  |1          | 2           | male
|Bob  |1          | 2           | female

如果有人知道一种简单的方法来获得我想要的结果吗? 我简化了表格,使其更具可读性。 谢谢你的时间,再次抱歉这个可怜的英语。

2 个答案:

答案 0 :(得分:0)

您可以在子查询上进行连接,该子查询将检索由contact_id和attribute_id分组的最大创建和其他值

类似的东西

select c.name, cv.contact_id, cv.attribute_id, cv.value
from contact c
join contact_value cv on cv.contact_id = c.id
join
    (select max(creation) as maxCreation, contact_id, attribute_id
     from contact_value
     group by contact_id, attribute_id) s
  on cv.contact_id = s.contact_id and 
     cv.attribute_id = s.attribute_id and 
     cv.creation = s.maxCreation

请参阅SqlFiddle

答案 1 :(得分:0)

您还可以在子查询中使用ORDER BYLIMIT 1

SELECT c.*,
(
  SELECT v.value
  FROM contact_value AS v
  WHERE v.contact_id = c.id
  ORDER BY v.creation
  LIMIT 1
) AS latest_value
FROM contact AS c
WHERE c.id = '1'