簡體   English   中英

MySQL僅獲取特定字段具有唯一值的行

[英]MySQL get only rows with a unique value for a certain field

我只想為特定字段(實際上是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__"))偽代碼中的if ((senderID == '1' && "__ receiverID is not yet listed__") || (receiverID == '1' && "__ senderID is not yet listed__"))

最終的返回值應該是(0, 1)

如何在(My)SQL中執行此操作? 我確實知道如何使用PHP來執行此操作,但是當有成千上萬的記錄時,它的速度就不夠快了。

親切的問候,

提姆

如果執行此操作,您將在發送方和接收方獲得所有唯一ID。

此外,UNION將合並兩個結果。

按照您的邏輯,如果您需要對發送/接收的ID分別進行操作,則可以使用第二列的值('S'/'R')來過濾兩個集合。

SELECT distinct id, 'S' as Type FROM table WHERE senderID='1' 
UNION
SELECT distinct id, 'R' as Type FROM table WHERE receiverID='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 |
+---------+

就像是

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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM