我有以下查询
SELECT
`c`.`id` AS `confession_id`,
`c`.`account_id` AS `confession_author_id`,
`c`.`confession_text`,
`c`.`anonymous`,
`c`.`total_likes`,
`c`.`total_comments`,
`c`.`creation_date`,
`a`.`username`,
`col`.`name` AS `college`,
`col`.`avatar_url`,
`cll`.`deleted` AS `tacc_exists`
FROM
`confessions` AS `c`
LEFT JOIN `accounts` AS `a`
ON `a`.`id` = `c`.`account_id`
LEFT JOIN `colleges` AS `col`
ON `col`.`id` = `c`.`college_id`
LEFT JOIN `confession_likes_log` AS `cll`
ON `cll`.`confession_id` = `c`.`id`
AND `cll`.`account_id` = :taccd_user
AND `c`.`college_id` IN ('9')
ORDER BY `c`.`id` DESC
LIMIT 10
假设根据提供的大学ID选择指定大学的条目
AND `c`.`college_id` in ('9')
虽然由于某种原因,即使college_id不是指定的那个,它也在选择条目。我在查找如何使用左连接执行和子句时遇到了麻烦,所以我可能没有正确地格式化查询。
答案 0 :(得分:1)
这是您的where
条款:
FROM `confessions` AS `c` LEFT JOIN
`colleges` AS `col`
ON `col`.`id` = `c`.`college_id` LEFT JOIN
`confession_likes_log` AS `cll`
ON `cll`.`confession_id` = `c`.`id` AND
`cll`.`account_id` = :taccd_user AND
`c`.`college_id` in ('9')
left join
的工作方式是:在on
子句中运行测试。如果第一个表中的给定行不匹配,则包括右表中具有NULL
值的行。你猜怎么着。这甚至适用于第一个表中的条件。
所以,过滤器c.college_id in ('9') isn't doing what you think. You need to move it to a
where where子句:
FROM `confessions` AS `c` LEFT JOIN
`colleges` AS `col`
ON `col`.`id` = `c`.`college_id` LEFT JOIN
`confession_likes_log` AS `cll`
ON `cll`.`confession_id` = `c`.`id` AND
`cll`.`account_id` = :taccd_user
WHERE `c`.`college_id` in ('9')