我正在尝试使用连接几个表的OR
条件,但是仅当用户位于eventParticipant
表(eventParticipant = ?
)中时它才有效,但是查询不返回任何内容如果用户是事件组织者(event.user_id = ?
)
$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);
答案 0 :(得分:2)
默认联接类型为INNER
。这要求在两个表中都找到该记录(例如,在eventParticipant
中找到该用户)。您需要在表之一中找到记录。为此,您需要一个OUTER JOIN
(您可以将JOIN eventParticipant
替换为LEFT JOIN eventParticipant
,这意味着left outer join
),因此即使有eventParticipant
表也将被联接没有匹配的记录(在这种情况下,eventParticipant.user_id将返回null)。然后WHERE
将过滤您需要的记录