【问题标题】:MySQL get only rows with a unique value for a certain fieldMySQL仅获取特定字段具有唯一值的行
【发布时间】:2010-10-10 12:44:04
【问题描述】:

我只想获取某个字段(实际上是 2 个)具有唯一值的行。 我的桌子是这样的:

id    senderID    receiverID    ...    ...    ...
_________________________________________________
0     0           1             ...    ...    ...
1     2           1             ...    ...    ...
2     1           0             ...    ...    ...
3     0           2             ...    ...    ...
4     2           0             ...    ...    ...
5     1           2             ...    ...    ...

在此表中,id始终是唯一的。 senderID 是发送消息的用户 ID,receiverID 是接收消息的用户 ID。 ... 是一些无关紧要的字段(例如 text),它们也不是唯一的。

首先,我想获取我(#1)是发送者或接收者的所有行。

SQL: "SELECT id FROM table WHERE senderID='1' OR receiverID='1'";

这将返回(0, 1, 2, 5)

但是现在,我只想要所有唯一的记录。 所以条件是:

  1. 1 应该是 senderID 或 receiverID。
  2. if ((senderID == '1' && "__ receiverID is not yet listed__") || (receiverID == '1' && "__ senderID is not yet listed__")) 伪代码。

最终返回应该是(0, 1)

如何在(我的)SQL 中执行此操作?我确实知道如何使用 PHP 来做到这一点,但是当有数千条记录时,它就不够快了。

亲切的问候,

提姆

【问题讨论】:

  • 所以你想要两个查询的结果一个?如果为真,您必须使用 PHP 对结果进行排序。

标签: sql mysql field unique


【解决方案1】:
select min(id) from 
(
  select id, senderID pID from table where receiverID = '1'
  union
  select id, receiverID pID from table where senderID = '1'
) as fred
group by pID;

对于您的数据集,这给出:

+---------+
| min(id) |
+---------+
|       0 |
|       1 |
+---------+

【讨论】:

  • 哇,谢谢马丁!这对我来说太棒了。它完全符合我的要求,我不需要使用多个 mysql_query 调用。非常非常感谢!
【解决方案2】:

如果您这样做,您将在您作为发送者的地方获得所有不同的 ID,在您作为接收者的地方获得不同的 ID。

此外,UNION 将合并这两个结果。

在您的逻辑中,如果您需要为发送/接收的 id 单独执行操作,您可以使用第二列值 ('S'/'R') 来过滤分离的 2 个集合。

SELECT distinct id, 'S' as Type FROM table WHERE senderID='1' 
UNION
SELECT distinct id, 'R' as Type FROM table WHERE receiverID='1' 

【讨论】:

  • 嗨,InSane,非常感谢。这也非常接近。我确实需要从 DISTINCT 中删除 id 字段。之后我得到:{receiverID='someReceiverID',receiverID='someReceiverID',receiverID='someSenderID'}。然后我使用第二个 SQL:“SELECT id FROM table WHERE (senderID='1' AND receiverID='$receiverID') OR (senderID='$receiverID' AND receiverID='1') ORDER BY date DESC LIMIT 0, 1 " 获取线程中最新消息的 ID。
【解决方案3】:

有点像

SELECT DISTINCT id, senderID, receiverID FROM table WHERE senderID='1' OR receiverID='1';

?

DISTINCT 关键字将从结果中删除所有重复项。到目前为止效果很好,除了 id、senderID 和 receiverID 之外,您没有添加任何其他列。

否则你也可以使用GROUP BY 子句

SELECT id FROM table WHERE senderID='1' OR receiverID='1' GROUP BY senderID, receiverID;

【讨论】:

  • 您好曾,谢谢您的回答!第一个(DISTINCT)根本不过滤,因为“id”字段对于每一行都是唯一的。第二个(GROUP BY)非常接近,但仍然返回每一行的 ID(但是,按线程/对话排序)。但是,通过将您的答案与 InSane 相结合,我得到了它的工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2011-04-03
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多