我正在尝试使用连接几个表的OR条件,但是仅当用户位于eventParticipant表(eventParticipant = ?)中时才有效,但是如果用户是事件组织者()

$query = $this->_db->prepare("SELECT event.event_id,
                                    event.user_id,
                                    event.sport_id,
                                    event.created,
                                    event.event_date,
                                    event.public,
                                    places.name as event_location,
                                    places.country,
                                    places.city,
                                    places.lat,
                                    places.lng,
                                    places.zipCode,
                                    event.description,
                                    event.cost,
                                    event.maxParticipant,
                                    tennis.fieldType,
                                    tennis.matchType,
                                    sportSupported.sport_name as tableName
                                    FROM event
                                    JOIN sportSupported on  event.sport_id = sportSupported.sport_id
                                    JOIN places on  event.place_id = places.place_id
                                    JOIN eventParticipant on eventParticipant.event_id = event.event_id
                                    JOIN tennis on tennis.event_id = event.event_id
                                    WHERE (event.user_id = ? OR eventParticipant.user_id = ?)");

$query->bindParam(1, $id, PDO::PARAM_INT);
$query->bindParam(2, $id, PDO::PARAM_INT);

if ($query->execute()){
    $result = $query->fetchAll(PDO::FETCH_ASSOC);
    $data["data"] =  $result;
    //....other stuff.....
}
return json_encode($data, JSON_PRETTY_PRINT);

最佳答案

默认联接类型为INNER。这要求在两个表中都找到该记录(例如,在eventParticipant中找到该用户)。您需要在其中一个表中找到该记录。为此,您需要一个OUTER JOIN(您可以将JOIN eventParticipant替换为LEFT JOIN eventParticipant,这意味着left outer join),因此即使没有匹配的记录,eventParticipant表也将被联接(对于eventParticipant,它将返回null .user_id)。然后WHERE将过滤您需要的记录

关于mysql - Mysql`OR`条件不适用于JOIN,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/57513799/

10-11 01:36