【问题标题】:select from table where both id exist从两个 id 都存在的表中选择
【发布时间】:2015-06-30 23:37:49
【问题描述】:

我需要从一个表中进行选择,其中两个 id 都存在于另一列中具有匹配 id 的列中。 我的查询如下所示,它给出的行甚至只有一个匹配的 id。

select * from customer_appdata where appdata_id in(11,12) 

id  customer_id appdata_id  
6    65             4
7    65             12  
8    65             8   
9    66             11  
10   66             12

所以在这里我只想要最后一行和倒数第二行(9,10),因为它们同时具有 11 和 12,公共 ID 为 66。

【问题讨论】:

  • 11,12 与 9,10 或 66 有什么关系?使困惑。请澄清你的问题。不清楚。请指定数据库平台。
  • 你能有多个记录具有相同的customer_id和相同的appdata_id吗?
  • select * from customer_appdata where appdata_id in(11,12) AND customer_id = 66 不是吗?你的问题真的不清楚。
  • 您想只查找只有这些 appdata_id 的客户,还是同时拥有这两个 appdata_id 的客户(但可以有额外的)?

标签: sql


【解决方案1】:

如果我正确理解了问题,这应该可以:

select * from customer_appdata where customer_id in (
  select customer_id from customer_appdata
  where appdata_id in (11,12) 
  group by customer_id
  having count(distinct appdata_id) = 2
)

您会找到所有重复特定次数的 customer_id(即内部查询),然后选择具有这些 customer_id 的所有行。可能有更快的方法,但如果性能不重要,这是解决问题的简单方法。

【讨论】:

  • 我编辑了答案,因为我刚刚意识到你想要解决的真正问题。第一个版本会做一些与你预期不同的事情。
  • 你需要把count(distinct appdata_id) = 2改为count(appdata_id) > 2。appdata_id可以大于2
  • distinct appdata_id 不能超过两个,因为我只根据两个值过滤它们。这是确保我匹配组中的 11 和 12 所必需的。
【解决方案2】:

此查询选择 customer_appdata 为 12 或 11 的行,并使用 exists 查看另一行是否也在表中。

select * from customer_appdata c1
where appdata_id in (11,12)
and exists (
    select 1 from customer_appdata c2
    where c2.appdata_id in (11,12)
    and c2.appdata_id <> c1.appdata_id
    and c2.customer_id = c1.customer_id
)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-01-12
    相关资源
    最近更新 更多