Mysql `OR` 条件不适用于 JOIN

标签 mysql

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

相关文章:

java - 日期之间的Mysql不起作用

java - Spring JDBC MySQL/MariaDB 数据在第 1 行的 'start_date' 列被截断

php - SELECT 所有数据行,但消除单列中具有重复数据的行

php - 如何使用 table2 中的检查字段将数据插入 table1 (Codeigniter)

mysql - Blob 和存储要求

mysql - 网站被利用,疑似SQL注入(inject)+PHP检查绕过,但无法解释后者是如何进行的

php - 选择未被阻止的用户 - SQL

php - 无法使用PHP获取MySql输出

java - 当自动提交设置为 false 时,select 是否返回最后插入的行?

mysql - SQL按名称对相似表进行分组