即使 MySQL子查询返回多个结果,是否有人想出一种方法可以使此代码正常工作?当用户没有与他相关的事件,或者当用户有一个与他相关的事件时,但当用户与多个事件相关时,子查询返回多个结果,而且代码无法使用。
$stmt = $db->prepare("SELECT * FROM events WHERE
id_events = ( SELECT id_events FROM relationship_events WHERE id_user = ?)");
$stmt->bindParam(1, $idUser);
$stmt->execute();
$rawTimeStamps = $stmt->fetchAll(PDO::FETCH_ASSOC);
$cleanDateArray = array();
foreach ($rawTimeStamps as $t) {
$rawDate = $t['start'];
$rawDate = getdate($rawDate);
$cleanDate = mktime(0,0,0,$rawDate['mon'],$rawDate['mday'],$rawDate['year']);
$cleanDateArray[] = $cleanDate;
}
for($list_day = 1; $list_day <= $days_in_month; $list_day++):
$calendar.= '<td class="calendar-day">';
$timestamp = mktime(0,0,0,$month,$list_day,$year);
if (!empty($cleanDateArray) && in_array($timestamp, $cleanDateArray)) {
$date = getdate($timestamp);
$time_start = mktime(0,0,0,$date['mon'],$date['mday'],$date['year']);
$time_end = mktime(23,59,59,$date['mon'],$date['mday'],$date['year']);
$stmt = $db->prepare('SELECT title FROM events WHERE start BETWEEN ? AND ?');
$stmt->bindParam(1,$time_start,PDO::PARAM_INT);
$stmt->bindParam(2,$time_end,PDO::PARAM_INT);
$stmt->execute();
$events = $stmt->fetch(PDO::FETCH_ASSOC);
$calendar.= '<div class="day-number day-number-event"><a href="#">'.$list_day.'</a></div><p>'.$events["title"].'</p>';
} else {
$calendar.= '<div class="day-number day-number-noevent">'.$list_day.'</div><div id="calendar-events"></div>';
}
答案 0 :(得分:3)
查询应为SELECT * FROM events WHERE id_events IN ( SELECT id_events FROM relationship_events WHERE id_user = ?)
。
答案 1 :(得分:1)
有两种可能的答案,具体取决于您希望它如何工作。
如果您只想要一个事件,无论用户是否有一个或多个事件,您都可以在子查询中添加LIMIT 1
:
SELECT * FROM events
WHERE id_events = (
SELECT id_events FROM relationship_events WHERE id_user = ? LIMIT 1
)
另一方面,如果您希望分配给用户的所有事件,您可以使用IN
子句:
SELECT * FROM events
WHERE id_events IN (
SELECT id_events FROM relationship_events WHERE id_user = ?
)
如果没有为用户分配任何事件,这两项工作也可以正常工作。