MySQL按照2条记录排序
MySQL sorting according to 2 records
我有这个 table 并记录:
Table: advertiser
id | company_id | start_date | end_date
----+----------------+----------------+-------------
1 | 2 | 2016-08-01 | 2016-10-12
2 | 3 | 2016-09-14 | 2016-12-01
3 | 2 | 2016-10-15 | 2017-02-10
我想 select 从这个 table 中按 start_date
排序记录 group by company_id
但是因为我按 company_id
分组所以我只能 select id:3 所以在对这条记录进行排序时显示在列表的末尾。
这是我的查询:
SELECT id
FROM advertiser
WHERE end_date >= NOW()
GROUP BY company_id
ORDER BY start_date ASC
和 selected 记录 ID 将是:
first: 2
second: 3
我怎样才能select这样记录?
first: 3
second: 2
更新:
我忘记在查询中添加 where
。
SELECT `id`, cia_last.`company_id`, `start_date`, `end_date`, mdate
FROM (
SELECT `id`, `company_id`, `start_date`, `end_date`,
@rn := if(@company_id = `company_id`,
@rn + 1,
if(@company_id := `company_id`,1,1)
) as rn
FROM advertiser
CROSS JOIN (SELECT @company_id := '', @rn := 0) as par
ORDER BY `company_id`, `start_date` desc
) cia_last
INNER JOIN ( SELECT `company_id`, MIN(`start_date`) as mdate
FROM advertiser
GROUP BY `company_id`) cia_first
ON cia_last.`company_id` = cia_first.`company_id`
WHERE rn = 1
ORDER BY mdate
我有这个 table 并记录:
Table: advertiser
id | company_id | start_date | end_date
----+----------------+----------------+-------------
1 | 2 | 2016-08-01 | 2016-10-12
2 | 3 | 2016-09-14 | 2016-12-01
3 | 2 | 2016-10-15 | 2017-02-10
我想 select 从这个 table 中按 start_date
排序记录 group by company_id
但是因为我按 company_id
分组所以我只能 select id:3 所以在对这条记录进行排序时显示在列表的末尾。
这是我的查询:
SELECT id
FROM advertiser
WHERE end_date >= NOW()
GROUP BY company_id
ORDER BY start_date ASC
和 selected 记录 ID 将是:
first: 2
second: 3
我怎样才能select这样记录?
first: 3
second: 2
更新:
我忘记在查询中添加 where
。
SELECT `id`, cia_last.`company_id`, `start_date`, `end_date`, mdate
FROM (
SELECT `id`, `company_id`, `start_date`, `end_date`,
@rn := if(@company_id = `company_id`,
@rn + 1,
if(@company_id := `company_id`,1,1)
) as rn
FROM advertiser
CROSS JOIN (SELECT @company_id := '', @rn := 0) as par
ORDER BY `company_id`, `start_date` desc
) cia_last
INNER JOIN ( SELECT `company_id`, MIN(`start_date`) as mdate
FROM advertiser
GROUP BY `company_id`) cia_first
ON cia_last.`company_id` = cia_first.`company_id`
WHERE rn = 1
ORDER BY mdate