gpt4 book ai didi

Mysql `OR` 条件不适用于 JOIN

转载 作者:行者123 更新时间:2023-11-29 06:29:08 25 4
gpt4 key购买 nike

我尝试使用 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);

最佳答案

默认连接类型是INNER。这要求在两个表中都找到记录(例如,在 eventParticipant 中找到用户)。您需要在其中一张表中找到该记录。为此,您需要一个OUTER JOIN(您只需将JOIN eventParticipant替换为LEFT JOIN eventParticipant,这意味着左外连接 code>),因此即使没有匹配的记录,eventParticipant表也会被连接(在这种情况下,eventParticipant.user_id将返回null)。然后WHERE会过滤你需要的记录

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com