我有一个Mark
个id
字段和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;
答案 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.coln
将marks.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;