是否可以从mySQL表中选择按当前日期按联接表值排序的行? 也许我显示出来。我有两个表:
一个国家的得分以日期分组。是否可以按当前日期分数对国家进行排序? 我有来自PHP阵列中表格的分数的国家:
$countries = array(
'England' =>
array('name', 'tag',
'scores' => array(
0 => array('date' => '2018-07', 'score' => 100),
1 => array('date' => '2018-08', 'score' => 50)
)),
'USA' =>
array('name', 'tag',
'scores' => array(
0 => array('date' => '2018-08', 'score' => 50),
1 => array('date' => '2018-09', 'score' => 20)
)
),
'France' =>
array('name', 'tag',
'scores' => array(
0 => array('date' => '2018-08', 'score' => 30),
1 => array('date' => '2018-09', 'score' => 100)
)
)
);
我需要选择按分数排序的当前日期所在的国家/地区。可以说当前日期为2018-09。我需要搜索国家/地区并按以下方式对其进行排序:
$countries = array(
'France' =>
array('name', 'tag',
'scores' => array(
0 => array('date' => '2018-08', 'score' => 30),
1 => array('date' => '2018-09', 'score' => 100)
)
),
'USA' =>
array('name', 'tag',
'scores' => array(
0 => array('date' => '2018-08', 'score' => 50),
1 => array('date' => '2018-09', 'score' => 20)
)
),
'England' =>
array('name', 'tag',
'scores' => array(
0 => array('date' => '2018-07', 'score' => 100),
1 => array('date' => '2018-08', 'score' => 50)
)),
);
从国家/地区选择c.name,s.date,s.score左联接得分s开启s.country_id = c.id GROUP BY日期ORDER BY(??)
答案 0 :(得分:0)
我们可以执行以下操作,获取每个date
的最新得分country_id
,以及最新score
的{{1}},然后按照值:
date
请注意,这假设 SELECT c.name
, s.date
, s.score
FROM country c
LEFT
JOIN score s
ON s.country_id = c.id
LEFT
JOIN ( SELECT m.country_id
, MAX(m.date) AS max_date
FROM score m
GROUP
BY m.country_id
) n
ON n.country_id = c.id
LEFT
JOIN score o
ON o.country_id = n.country_id
AND o.date = n.max_date
ORDER
BY o.date DESC
, o.score DESC
, c.name ASC
, s.date ASC
元组在(country_id,date)
表中是唯一的。如果没有保证,我们可以调整查询以适应这一点。像这样:
score