简体   繁体   中英

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? 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:

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:

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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