如何才能获得字段值只出现一次的所有行?

时间:2017-03-22 22:02:18

标签: mysql sql

希望你能理解我要存档的内容......

我有类似的东西

table:my_user

id - username - user_profile - user_status - user_key

所以,如果我有这样的内容

1 - John Doe - profile1 - ok - key12345
2 - John Doe - profile2 - ok - key12345
3 - John Doe - profile2 - ok - key12345
4 - John Doe - profile2 - ok - key12346
5 - John Doe - profile2 - ok - key12347

我确实拥有所有不同的键,例如

key12345
key12346
key12347

在查询中是否有任何方法可以查询我的表,询问所有匹配的结果是否具有此键但是只检索第一个包含它的记录?像:

1 - John Doe - profile1 - ok - key12345
4 - John Doe - profile2 - ok - key12346
5 - John Doe - profile2 - ok - key12347

我试过这样的事情

select * from my_user where user_key IN (key12345, key12346, key12347)

但我得到所有的行,是否可以这样做?

2 个答案:

答案 0 :(得分:2)

您可以尝试以下查询:

#include <memory>

struct MyClass {
    void open() {
        // note - may throw
    };

    void close() noexcept {
        // pre - is open
    }
};

struct Closer
{
    void operator()(MyClass* p) const noexcept
    {
        p->close();
        delete p;  // or return to pool, etc
    }
};

auto CreateMyClass() -> std::unique_ptr<MyClass, Closer>
{
    // first construct with normal deleter
    auto p1 = std::make_unique<MyClass>();

    // in case this throws an exception.
    p1->open();

    // now it's open, we need a more comprehensive deleter
    auto p = std::unique_ptr<MyClass, Closer> { p1.release(), Closer() };
    return p;
}

int main()
{
    auto sp = std::shared_ptr<MyClass>(CreateMyClass());
}

这里是 SQL Fiddle

答案 1 :(得分:2)

使用变量模拟row_number()

<强> SQL Demo

SELECT *
FROM (
       SELECT my_user.*,
              @rn := IF(@user = user_key,
                        @rn + 1,
                        IF(@user:= user_key, 1, 1)
                       ) as rn         
       FROM my_user 
       CROSS JOIN (SELECT @rn := 0, @user := 0) t
       where user_key IN ('key12345', 'key12346', 'key12347')
       ORDER BY user_key
     ) F
WHERE F.rn = 1
ORDER BY id;

<强>输出

enter image description here