简体   繁体   English

MySQL子查询返回多个结果

[英]MySQL subquery returning more than one result

Does someone figures out a way to make this code works even when MySQL subquery returns more than one result? 有人能找到一种使该代码即使在MySQL子查询返回多个结果的情况下也能起作用的方法吗? It is working fine when the user has no event related to him, or when the user has one event related to him, but when a user is related to more than one event , the subquery returns more than one result and than the code gets nothing to work with. 当用户没有与他有关的事件时,或者当用户有一个与他有关的事件时,它工作正常,但是当用户与一个以上事件有关时,子查询返回多个结果,并且代码没有任何结果跟...共事。

$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>';
    }

查询应该是SELECT * FROM events WHERE id_events IN ( SELECT id_events FROM relationship_events WHERE id_user = ?)

There are two possible answers, depending on how you want it to work. 有两个可能的答案,具体取决于您希望它如何工作。

If you only want a single event, regardless if the user has 1 or more events, you can add LIMIT 1 in your subquery: 如果只希望一个事件,无论用户是否有1个或多个事件,都可以在子查询中添加LIMIT 1

SELECT * FROM events
WHERE id_events = (
    SELECT id_events FROM relationship_events WHERE id_user = ? LIMIT 1
)

On the other hand, if you want all events assigned to the user, you can use an IN clause: 另一方面,如果要将所有事件分配给用户,则可以使用IN子句:

SELECT * FROM events
WHERE id_events IN (
    SELECT id_events FROM relationship_events WHERE id_user = ?
)

Both of these should also work fine if the user is assigned to no events. 如果未将用户分配给任何事件,则这两个选项也应正常工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM