有3个不同的mysql表,我的脚本使用JOINS查询数据库,以输出3个表中每个表的最新结果。所有的工作都应该像mysql数据库允许JOINS一样,ORDER BY会在列出表时对结果进行排序,导致完成的输出没有按日期正确排序,因为结果来自3个不同的MYSQL表。
结果改为按日期正确排序,仅在同一个表的其他结果旁边。请参阅下面的脚本和结果:(为简单起见,我的输出限制为1)
$username = $_SESSION['username'];
$result = $mysqli->query("
SELECT
accounts.account_name,
cases.case_subject,
tasks.task_title,
accounts.accounts_date_last_edited,
cases.cases_date_last_edited,
tasks.tasks_date_last_edited
FROM
accounts,
cases,
tasks
WHERE
accounts.username = cases.username
AND cases.username = tasks.username
ORDER BY
accounts.accounts_date_last_edited DESC,
cases.cases_date_last_edited DESC,
tasks.tasks_date_last_edited DESC
LIMIT 1
");
if (!$result) { echo "Error Result5: " . $mysqli->error; } else {
echo "<table>";
echo "<tr><th>Item</th><th>Date</th></tr>";
while ($row = $result->fetch_array(MYSQLI_ASSOC))
{
echo "<tr>";
echo "<td>" . $row['account_name'] . "</td><br>";
echo "<td>" . $row['accounts_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['case_subject'] . "</td><br>";
echo "<td>" . $row['cases_date_last_edited'] . "</td><br>";
echo "</tr>";
echo "<tr>";
echo "<td>" . $row['task_title'] . "</td><br>";
echo "<td>" . $row['tasks_date_last_edited'] . "</td><br>";
echo "</tr>";
}
echo "</table>";
结果如下:他们将列出上面列出的每个表中的1个项目。我再次尝试按date_last_edited排序,无论值来自哪个表。
Item Date
Shorley Homes 2013-11-02 04:02:34
Techical Testing Case Open 2013-11-03 07:17:36
Icons 2013-11-03 07:28:02
答案 0 :(得分:0)
如果我读得正确(我不确定)你的
...按
date_last_edited
排序,无论哪个值来自哪个表...
然后您可能希望使用UNION
代替JOIN
SELECT account_name item, accounts_date_last_edited date
FROM accounts
UNION ALL
SELECT case_subject, cases_date_last_edited
FROM cases
UNION ALL
SELECT task_title, tasks_date_last_edited
FROM tasks
ORDER BY date DESC
这是 SQLFiddle 演示