我有这两种表,一种用于保存文本等,另一种用于保存图像信息,
pages table
,
pg_id pg_content parent_id
10 xxx 3
11 xxx 3
12 xxx 3
image table
,
img_id pg_id img_order cat_id
1 10 1 1
2 10 1 2
3 10 2 2
4 11 1 1
所以我想仅列出来自img_order
1的cat_id
1张图片的所有页面,但当页面包含cat_id
2中的图片时,我会得到重复的行,
SELECT*
FROM root_pages
LEFT JOIN root_images_pages
ON root_images_pages.pg_id = root_pages.pg_id
WHERE root_pages.parent_id = '3'
AND root_pages.pg_id != '3'
AND (root_images_pages.img_order = '1' OR root_images_pages.img_id is NULL)
ORDER BY root_pages.pg_created DESC
LIMIT 12
我该如何解决?
我想要的结果是,
pg_id pg_content parent_id img_id pg_id img_order cat_id
10 xxx 3 1 10 1 1
11 xxx 3 4 11 1 1
12 xxx 3 null null null null
修改
我必须将以下行添加到查询中,否则无法列出没有图像的页面,
AND (i.img_order = '1' OR i.img_id is NULL)
所以在这里,
SELECT*
FROM root_pages p
LEFT JOIN root_images_pages i
ON i.pg_id = p.pg_id and i.cat_id = 1
WHERE p.parent_id = '3'
AND p.pg_id != '3'
AND p.pg_hide != '1'
AND (i.img_order = '1' OR i.img_id is NULL)
ORDER BY p.pg_created DESC
LIMIT 12
答案 0 :(得分:2)
在where子句中排除cat_id = 2?
WHERE .... AND (root_images_pages.cat_id <> 2)
或明确仅允许cat_id = 1?
WHERE .... AND (root_images_pages.cat_id = 1)
答案 1 :(得分:1)
尝试使用子查询选择页面,然后左键加入根图像
SELECT * FROM (SELECT * FROM root_images_pages WHERE cat_id = 1 ) AS i LEFT JOIN root_pages AS p ON i.pg_id = p.pg_id
答案 2 :(得分:1)
这个怎么样,我认为通过将cat_id标准添加到您的联接中,您可以获得您正在寻找的数据:
SELECT*
FROM root_pages r
LEFT JOIN root_images_pages i
ON i.pg_id = r.pg_id and i.cat_id = 1
WHERE r.parent_id = '3'
ORDER BY r.pg_created DESC
LIMIT 12
看到你的编辑后,我认为你需要切换JOIN条件。
LEFT JOIN root_images_pages i
ON r.pg_id = i.pg_id and i.cat_id = 1
答案 3 :(得分:0)
我相信马克有正确的答案。但我也认为你不需要:
OR root_images_pages.img_id is NULL
假设img_id是主键。