代码之家  ›  专栏  ›  技术社区  ›  cutsoy

MySQL只获取对某个字段具有唯一值的行

  •  1
  • cutsoy  · 技术社区  · 15 年前

    我的桌子是这样的:

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

    在这张桌子上, id 总是 senderID receiverID 是接收消息的用户的ID。 ... 一些字段(如 text

    因此,首先,我想得到所有行,其中我(#1)是发送者或接收者。

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

    这会回来的 (0, 1, 2, 5) .

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

    1. 1 应该是发件人ID或接收者ID。
    2. if ((senderID == '1' && "__ receiverID is not yet listed__") || (receiverID == '1' && "__ senderID is not yet listed__"))

    最后的回报应该是 (0, 1) .

    如何在(我的)SQL中执行此操作?我知道如何使用PHP来实现这一点,但是当有成千上万条记录时,它已经不够快了。

    谨致问候,

    提姆

    3 回复  |  直到 15 年前
        1
  •  2
  •   Martin    15 年前
    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 |
    +---------+
    
        2
  •  2
  •   Jagmag    15 年前

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

    SELECT distinct id, 'S' as Type FROM table WHERE senderID='1' 
    UNION
    SELECT distinct id, 'R' as Type FROM table WHERE receiverID='1' 
    
        3
  •  1
  •   Tseng    15 年前

    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;