SQL JOIN从第二个表中获取不同的列

时间:2011-11-06 15:08:33

标签: mysql sql join

我有一个Markid字段和name字段,第二个表mark_id以及我感兴趣的两个额外列。我想得到所有记录来自Mark表格+该商标的优先级和created_at。可能有几个created_at值,但我不太关心它们,我只需要一个(第一个,无论如何)。

我尝试过这个查询,它给了我太多记录,而不是我想要的5个。

SELECT 
    marks.*, 
    markings.created_at, 
    markings.created_at AS updated_at,
    markings.priority 
FROM `marks` 
JOIN markings 
    ON marks.id = markings.tag_id
WHERE (created_at > '2011-11-06 12:05:01') 
    AND (priority = 1) 
ORDER BY created_at;

2 个答案:

答案 0 :(得分:3)

SELECT 
    marks.*, 
    MIN(markings.created_at) as created_at, 
    MIN(markings.created_at) AS updated_at,
    markings.priority 
FROM `marks` 
JOIN markings 
    ON marks.id = markings.tag_id
WHERE (created_at > '2011-11-06 12:05:01') 
    AND (priority = 1) 
GROUP BY marks.col1, marks.col2, ... marks.coln, markings.priority
ORDER BY created_at;

如果您没有更多列,则marks.col1, marks.col2, ... marks.colnmarks.id, marks.name为{{1}}。

答案 1 :(得分:1)

此查询按标记和标识对结果进行分组,应该是您想要的结果:

   SELECT 
    marks.id, 
    MAX(markings.created_at), 
    MAX(markings.created_at) AS updated_at,
    markings.priority 
FROM `marks` 
JOIN markings 
    ON marks.id = markings.tag_id
WHERE (created_at > '2011-11-06 12:05:01') 
    AND (priority = 1) 
GROUP BY marks.id,markings.priority
ORDER BY updated_at;