这是我当前的查询:
SELECT `performers`.`hash`,
`performers`.`alias`,
`performers`.`date_updated`,
`performers`.`status`,
IF(`performers`.`status` = 'active', 'deleted','active') AS `statususe`,
`images`.`image_hash_file`
FROM `performers`
LEFT JOIN `images` ON `images`.`asset_id` = `performers`.`id`
WHERE (`images`.`asset_type` = 'performer')
ORDER BY `alias` ASC LIMIT 12`
其中有一个where子句
WHERE (`images`.`asset_type` = 'performer')
我希望它是可选的,这样如果where子句不合适,它仍会显示表演者表中没有连接到完成图像记录的记录。
答案 0 :(得分:1)
尝试这样的事情:
WHERE (`images`.`asset_type` = 'performer' OR `images`.`asset_type` IS NULL)
答案 1 :(得分:1)
您可以在LEFT JOIN中添加WHERE子句,因此不匹配的行仍在结果集中。
SELECT `performers`.`hash`, `performers`.`alias`,
`performers`.`date_updated`, `performers`.`status`,
IF(`performers`.`status` = 'active', 'deleted','active') AS `statususe`,
`images`.`image_hash_file`
FROM `performers`
LEFT JOIN `images` ON `images`.`asset_id` = `performers`.`id` AND `images`.`asset_type` = 'performer'
ORDER BY `alias` ASC
LIMIT 12
WHERE和ON子句之间的主要区别在于ON子句在JOIN期间工作,当WHERE子句在所有连接之后工作时,不会从结果集中删除匹配的行。
答案 2 :(得分:1)
您应该将where
条件移至on
子句:
SELECT p.`hash`, p.`alias`, p.`date_updated`, p.`status`,
IF(p.`status` = 'active', 'deleted', 'active') AS statususe,
i.`image_hash_file`
FROM `performers` p LEFT JOIN
`images`i
ON i.`asset_id` = p.`id` and
i.`asset_type` = 'performer'
ORDER BY `alias` ASC
LIMIT 12
我还修改了查询以使用表别名。它们使查询更容易编写和阅读。