我有一个左连接的SQL查询:
SELECT i.id
, i.user_id
, i.date
, h.cat_id
FROM io__image i
LEFT
JOIN io__image_cat_hext h
ON h.image_id = i.id
WHERE i.home_granted >= 1
AND user_id = 40
ORDER
BY i.date DESC
结果如下:
id user_id date cat_id
530 40 2018-05-12 20:45:54 42
528 40 2018-05-11 22:59:17 42
518 40 2018-05-11 17:22:30 42
508 40 2018-05-09 13:45:40 37
504 40 2018-05-06 22:40:31 37
492 40 2018-05-02 21:21:20 37
490 40 2018-05-02 16:16:09 36
481 40 2018-05-02 15:08:35 36
是否有可能获得DISTINCT cat_id?我试过Group by:
SELECT i.id
, i.user_id
, i.date
, h.cat_id
FROM io__image i
GROUP
BY h.cat_id
LEFT
JOIN io__image_cat_hext h
ON h.image_id = i.id
WHERE i.home_granted >= 1
AND user_id = 40
ORDER
BY i.date DESC
但是我收到了这个错误:
语法附近' LEFT JOIN io__image_cat_hext ON io__image_cat_hext.image_id = io__image.id WHER'第4行
答案 0 :(得分:2)
在此背景下,DISTINCT cat_id
很难理解你的确切含义。也许你正在寻找这样的东西?
SELECT io__image.id,
io__image.user_id,
io__image.date,
io__image_cat_hext.cat_id
FROM (SELECT max(io__image_cat_hext.image_id) image_id,
io__image_cat_hext.cat_id
FROM io__image_cat_hext
GROUP BY io__image_cat_hext.cat_id) io__image_cat_hext
INNER JOIN io__image
ON io__image.id = io__image_cat_hext.image_id
ORDER BY io__image.date DESC;
它只会为您提供每个类别ID最高的图片。如果ids是自动递增的,那就是最近插入的图像。
答案 1 :(得分:1)
如果您只想要cat_id
值,则可以执行以下操作:
select h.cat_id
from io__image i join
io__image_cat_hext h
on h.image_id = i.id
where i.home_granted >= 1 and i.user_id = 40
group by h.cat_id
order by max(i.date) desc;
如果没有显示您想要的结果,这似乎最适合您的问题。