【问题标题】:fetching a table with unique or distinct values?获取具有唯一或不同值的表?
【发布时间】:2011-01-29 01:49:07
【问题描述】:

我有这张桌子:

post{id, user_id, event_id}

我想为特定用户获取所有具有 event_id(非 NULL)的帖子,并且我不希望 event_id 再次发生,我希望它是不同的,即如果 2 个帖子的 event_id 为 2,那么我只需要检索其中一个,谢谢!!!

即

select count(*)
from posts
where user_id = '43'
and
//not null event id
//distinct event id's

【问题讨论】:

    标签: mysql tsql unique distinct


    【解决方案1】:

    试试这个来获取事件 id 的计数:

    SELECT COUNT(DISTINCT event_id)
    FROM   posts 
    WHERE  user_id = '43' 
      AND event_id IS NOT NULL 
    

    【讨论】:

    • 实际上,AND event_id IS NOT NULL 是不必要的,我认为。 NULL 不算数,是吗?
    【解决方案2】:

    试试

    select distinct event_id 
    from posts
    where user_id='43' and event_id is not null
    

    如果你需要 id 会有点复杂,但是可以使用这个

    select max(id)
    from posts
    where user_id='43' and event_id is not null
    group by event_id
    

    如果你想要第一个事件编号,你可以用 min(id) 替换 max(id)

    【讨论】:

    • 谢谢,但我想要计算结果!!有可能吗
    【解决方案3】:
    select event_id, count(event_id)
    from posts
    where user_id=43 and event_id is not null
    group by event_id;
    

    group by 是获取每个唯一 event_id 的计数

    【讨论】:

      猜你喜欢
      • 2020-03-19
      • 2019-02-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-03
      • 2013-10-05
      • 2016-06-07
      • 2021-01-10
      相关资源
      最近更新 更多