【问题标题】:Find the rows that has the same column查找具有相同列的行
【发布时间】:2017-04-18 13:17:47
【问题描述】:

我想知道如何在 SQL 中执行以下操作:

SELECT * 
FROM table_A 
WHERE id IN(:myValues)
AND other_colum has the same value

例如,如果我有一个会话表 (iduser,idconversation),我希望 SQL 查询返回一些具有相同会话 ID 的 Id。它应该返回

35;105
37;105
35;106
37;106

他们有 35,37 个 idUser 和 105,106 个对话。

为了更进一步,我使用 Doctrine 和 PostegreSQL,生成了我要查询的表 (多对多关系),但我很难集成子查询。

  **public function getAllCommonConversationByUserId($ids)
  {
      return $this->createQueryBuilder('c')
          ->select('c.id')
          ->innerJoin('c.idUser', 'recievedConversation')
          ->where('recievedConversation IN (:ids)')
          ->andWhere('$qb->expr()->eq("SELECT id FROM table GROUP BY(id) HAVING COUNT(*) >1")')
          ->setParameter(':ids', $ids)
          ->getQuery()
          ->getResult();
  }**

【问题讨论】:

  • 您使用的是哪个 DBMS?后格雷斯?甲骨文?
  • 我使用 PostgreSQL 和学说

标签: sql postgresql doctrine


【解决方案1】:

只是:

SELECT * 
FROM table_A 
WHERE idconversation in ('105','106') and iduser in ('35','37')

更新: 您是说 idconversation 是否重复? (显示多次?)

如果是这样:

Select * 
From table 
where idconversation in 
(
Select idconversation 
From table
group by (idconversation)
Having count(*) >1
)
--where iduser in ('35','37')

【讨论】:

  • 不告诉对话的ID。我只需要告诉 idUser 和 SQL 必须返回给我他们共同的 idConversation
  • 是的,这就是我想要的。我正在使用 Doctrine,但我没能做到(因为子查询集成)
  • 我对那个产品不熟悉,抱歉:(
【解决方案2】:

尝试这样做:

select id, conversation
from [your table name]
where 
    conversation in (
        select conversation 
        from [your table name]
        where id in (35)
    )

它返回用户 id = 35 的所有对话参与者

如果您的表中有重复项,请在 select 语句中添加 distinct

【讨论】:

    【解决方案3】:

    您可以使用group byhaving 获取对话:

    SELECT conversationid
    FROM table_A 
    WHERE userid in (35, 37)
    GROUP BY userid
    HAVING count(distinct userid) = 2;
    

    如果您想要原始行,您可以连接回原始表。

    【讨论】:

    • 您的查询中是否有 35 和 37 个用户 ID?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-27
    • 2012-06-18
    • 1970-01-01
    • 2016-05-21
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    相关资源
    最近更新 更多