简体   繁体   English

如何选择两个字段唯一的记录

[英]How to select records where two fields are unique

I have a table that looks something like this: 我有一张桌子,看起来像这样:

+-------------+----------+---------------+------------+
| Contract_ID |   Name   |   Username    |  Password  |
+-------------+----------+---------------+------------+
|    12345671 | Facebook | john.doe      | password   |
|    12345672 | Google   | john.doe      | password   |
|    12345673 | Apple    | martha.malone | doodlebear |
|    12345674 | Samsung  | jimmy47       | parkour445 |
|    12345675 | HTC      | rick.grimes   | simpsons33 |
+-------------+----------+---------------+------------+

I'd like to select only records where there is a one to one ratio between username/password combination and contract id. 我只想选择用户名/密码组合与合同ID之间存在一对一比率的记录。 In this case, that would mean I'd like to select the 3rd, 4th and 5th records in this table. 在这种情况下,这意味着我想在此表中选择第3、4和5条记录。

I've tried different combinations of the DISTINCT keyword but that doesn't seem to be the correct route to go. 我尝试过DISTINCT关键字的不同组合,但这似乎并不是正确的选择。 Is there a query that can return this information? 是否存在可以返回此信息的查询?

As a sort of bonus question: is there a query that can produce the opposite results (ie. only records where there is greater than 1 to 1 ratio between contract ids and username/password combination)? 作为一种奖励问题:是否存在可以产生相反结果的查询(即,仅记录合同ID与用户名/密码组合之间的比率大于1:1的记录)?

You should use the GROUP BY clause together with the HAVING clause, for example: 您应该将GROUP BY子句与HAVING子句一起使用,例如:

SELECT Username, Password FROM Table
GROUP BY Username, Password
HAVING COUNT(*) = 1

The opposite is: 相反的是:

SELECT Username, Password FROM Table
GROUP BY Username, Password
HAVING COUNT(*) > 1

按(名称,密码)分组不起作用?

Very naughty way of doing it,not good at all, but it works: 这样做很顽皮,一点也不好,但是可以用:

    select distinct
    least(col1, col2) as value1
  , greatest(col1, col2) as value2
from yourtable

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

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