简体   繁体   English

MySQL DISTINCT放在一栏和左联接

[英]MySQL DISTINCT on one column and LEFT JOIN

I have a SQL query with a left join: 我有一个左连接的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

Result looks like: 结果看起来像:

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

Would it be possible to get DISTINCT cat_id? 可以获取DISTINCT cat_id吗? I tried with Group by: 我尝试了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

But I get this error: 但是我得到这个错误:

Syntax near 'LEFT JOIN io__image_cat_hext ON io__image_cat_hext.image_id = io__image.id WHER' on line 4 第4行上'LEFT JOIN io__image_cat_hext ON io__image_cat_hext.image_id = io__image.id WHER'附近的语法

It's hard to understand what you exactly mean by DISTINCT cat_id in this context. 在这种情况下,很难理解DISTINCT cat_id确切含义。 Maybe you are searching for something like this? 也许您正在搜索类似的东西?

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;

It'll give you only the image with the highest id for each category. 它只会为您提供每个类别ID最高的图像。 If the ids are auto incremented, that's the image inserted most recently. 如果ID是自动递增的,则是最近插入的图像。

If you want only the cat_id values, then you can do: 如果只需要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;

Without showing the results you want, this seems like the best fit to your question. 没有显示您想要的结果,这似乎最适合您的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM