我正在尝试列出两个表doc_to_do
的最新更新,下面的doc_bug_tracker
是我的表结构
doc_to_do
doc_bug_tracker
这是我当前的查询:
$sth = $this->db->prepare('SELECT p.*,
dtd.projects_id as dtd_projects_id, dtd.content as dtd_content, dtd.date_modified as dtd_date_modified,
dbt.projects_id as dbt_projects_id, dbt.content as dbt_content, dbt.date_modified as dbt_date_modified
FROM `projects` p LEFT JOIN `doc_to_do` dtd ON p.id=dtd.projects_id
LEFT JOIN `doc_bug_tracker` dbt ON p.id=dbt.projects_id
where p.id="'.$project_id.'"');
现在如何从表date_modified
或doc_to_do
doc_bug_tracker
订购?
答案 0 :(得分:1)
要获取 最新日期(而不是所有日期,按顺序降序),请尝试以下操作:
SELECT
p.id,
MAX(GREATEST(dtd.date_modified, dbt.date_modified)) AS MaxDate
FROM projects p
LEFT JOIN doc_to_do dtd ON p.id = dtd.projects_id
LEFT JOIN doc_bug_tracker dbt ON p.id = dbt.projects_id
WHERE p.id = <project_id>
GROUP BY p.id
如果您需要在SELECT
中添加其他列,请务必将其添加到GROUP BY
。
答案 1 :(得分:0)
这应该有效:
'SELECT x.* FROM
(
SELECT p.*,
dtd.projects_id as dtd_projects_id, dtd.content as dtd_content, dtd.date_modified as dtd_date_modified,
dbt.projects_id as dbt_projects_id, dbt.content as dbt_content, dbt.date_modified as dbt_date_modified
FROM `projects` p LEFT JOIN `doc_to_do` dtd ON p.id=dtd.projects_id
LEFT JOIN `doc_bug_tracker` dbt ON p.id=dbt.projects_id
where p.id="'.$project_id.'"
) x
ORDER BY x.date_modified ASC'