我有三个这样的数据库表:
movies_tbl(id,name,...)
category_relation_tbl(row,movie_id,category_id,is_delete, ...)
categories_tbl(id,name_fa,is_delete,...)
在此数据库中,is_delete表示记录已删除。我有这样的查询,以获取所有具有类别的电影:
SELECT movies_tbl.* , GROUP_CONCAT(DISTINCT(categories_tbl.name_fa)) as category_names
FROM movies_tbl
LEFT JOIN category_relation_tbl ON category_relation_tbl.movie_id = movies_tbl.id
LEFT JOIN categories_tbl ON categories_tbl.id = category_relation_tbl.category_id
WHERE movies_tbl.is_delete = 0
GROUP BY movies_tbl.id
我应该如何获得所有带有类别的电影,即使它们没有任何类别,又该如何检查category_relation_tbl.is_delete = 0? 当我检查(category_relation_tbl.is_delete)时,MySQL只返回在category_relation_tbl中具有相关数据的电影!
答案 0 :(得分:4)
您可以在category_relation_tbl.is_delete = 0
之后添加LEFT JOIN
SELECT movies_tbl.* , GROUP_CONCAT(DISTICT(categories_tbl.name_fa)) as category_names
FROM movies_tbl
LEFT JOIN category_relation_tbl ON category_relation_tbl.movie_id = movies_tbl.id
AND category_relation_tbl.is_delete = 0
LEFT JOIN categories_tbl ON categories_tbl.id = category_relation_tbl.category_id
GROUP BY movies_tbl.id