你看我试图在我的数据库中列出一个表的记录,但我想用以下方式来做:
在我的数据库表中,我有4个字段:
id, task, date, time
例如,在一天中执行多个任务,但在不同时间执行。然后我在我的数据库中存储了不同日期和不同时间的许多任务。我想要的是每天列出它们。查阅数据库并显示首先显示日期的列表,然后显示在该日期完成的所有任务,然后显示该日期的其他日期和所有任务,依此类推。
像这样的东西
那是我的PHP代码
$obj = new Task();
$consult = $obj->Lists();
date_default_timezone_set("America/Mexico_City");
$dateActual = date("Y-m-d");
while ($result = $consult->fetch_object()) {
echo "<button class='btn btn-default'>date = " . $result->date . "</button><br>";
$consult2 = $obj->Lists2($dateActual);
while($result2 = $consult2->fetch_object()) {
echo "<span>". $result2->time ."</span><br>";
}
$dateActual = $result->date;
}
我对数据库的查询是:
public function Lists2($date)
{
global $conexion;
$sql = "SELECT ar.*, date_format(ar.date, '%d/%m/%Y') as date,
date_format(ar.time, '%r') as time,
u.user as User
FROM task_recents ar
INNER JOIN user u ON ar.iduser = u.iduser
WHERE date = '$date'
ORDER BY ar.time DESC";
$query = $conexion->query($sql);
return $query;
}
public function Lists()
{
global $conexion;
$sql = "SELECT ar.*, date_format(ar.date, '%d/%m/%Y') as date,
date_format(ar.time, '%r') as time,
u.user as User
FROM task_recents ar
INNER JOIN user u ON ar.iduser = u.iduser
ORDER BY ar.time DESC";
$query = $conexion->query($sql);
return $query;
}
结果是它显示了重复的日期及其各自的记录。
我想要达到的目标是:
我怎么能这样做?
PD:我得到的结果是:
但我不喜欢那样......
答案 0 :(得分:0)
只要列之间存在匹配项,INNER JOIN关键字就会选择两个表中的所有行。如果&#34;订单中有记录&#34;在&#34;客户&#34;中没有匹配的表格,这些订单将不会显示!
以下查询不应再生成重复记录
SELECT
ar.id,
ar.task,
date_format(ar.date, '%d/%m/%Y') as formattedDate,
date_format(ar.time, '%r') as formattedTime,
u.user as User
FROM
task_recents ar
LEFT JOIN
user u
ON
u.iduser = ar.iduser
WHERE
date = '$date'
ORDER BY
ar.time
DESC