获取两个表中的一个中最旧的行

时间:2017-12-28 16:38:27

标签: mysql

所以我现在有一个相当复杂的查询,如下所示:

SELECT keywords.id as keyword_id,
       keywords.keyword as keyword,
       i.id as position_id,
       i.position as position,
       i.created_at as created_at
FROM keywords
LEFT JOIN positions i
  ON  i.keyword_id = keywords.id
  AND i.id >= COALESCE((
    SELECT i1.id
    FROM positions i1
    WHERE i1.keyword_id = keywords.id
    ORDER BY i1.id DESC
    LIMIT 1
    OFFSET 1
  ), 0)
WHERE keywords.website_id = ?
ORDER BY keywords.keyword ASC, i.id ASC', [$this->id]);

所以现在我正在尝试向查询添加其他数据。我需要positionsposition_backups表中最旧的行(基于created_at列)。我需要首先检查position_backups中最旧的行,如果找不到,那么positionskeyword_id的最新行。 SELECT keywords.id as keyword_id, keywords.keyword as keyword, i.id as position_id, i.position as position, i.url as url, i.created_at as created_at, ifnull ((select position from position_backups WHERE keyword_id = keywords.id ORDER BY id ASC LIMIT 1), (select position from positions WHERE keyword_id = keywords.id ORDER BY id ASC LIMIT 1)) as first_position FROM keywords LEFT JOIN positions i ON i.keyword_id = keywords.id AND i.id >= COALESCE(( SELECT i1.id FROM positions i1 WHERE i1.keyword_id = keywords.id ORDER BY i1.id DESC LIMIT 1 OFFSET 1 ), 0) WHERE keywords.website_id = 20 ORDER BY keywords.keyword ASC, i.id ASC

任何人都可以告诉我如何完成这项工作吗?我搜索了很多,但还没找到我想要的东西。

这是我到目前为止所拥有的。我不确定它是否完全符合我的要求,因为我需要更多地测试它。任何意见或建议表示赞赏。

def list = [[field:A, amount:1000], [field:A, amount:2000], [field:B, amount:3000], [field:C, amount:4000]]

0 个答案:

没有答案