【问题标题】:Query that will match a non-unique id if there is data in two separate columns across multiple rows如果跨多行的两个单独列中存在数据,则将匹配非唯一 id 的查询
【发布时间】:2017-09-08 04:16:05
【问题描述】:

我一直在试图弄清楚如何从单个表中提取数据。如果跨多行的两个单独列中有数据,我需要一个匹配 id(非唯一)的查询。以下是数据示例。

+---------+---------------+-----------+
|     id  |  Drivers      | Brands    |
+---------+---------------+-----------+
|    1    |               |  Brands   |
|    2    |   Drivers     |           | 
|    3    |   Drivers     |           | 
|    1    |   Drivers     |           | 
|    4    |               | Brands    | 
|    2    |   Drivers     |           | 
|    3    |               | Brands    | 
|    4    |               | Brands    | 
+---------+---------------+-----------+

Id 1 和 3 是唯一同时包含 Drivers 和 Brands 值的行。这是我需要的数据。

关于数据的几件事:

  • 司机和品牌永远不会发生争执。
  • 一个 id 可能会有多行,只有 Driver 或 Brands(不能使用 count 来确定匹配)。

【问题讨论】:

  • 那么你想要的结果是1和3?
  • 正确。 Id 1 和 3 是我想要的。 1 和 3 是唯一在 Drivers 和 Brands 中都有值的 id。

标签: sql postgresql


【解决方案1】:

您可以发送GROUP BY。使用 HAVING 子句返回具有驱动程序和品牌值的 ID:

select id
from tablename
group by id
having count(drivers) > 0 and count(brands) > 0

或者,使用INTERSECT:

select id from tablename where drivers is not null
intersect
select id from tablename where brands is not null

INTERSECT 返回两个选择的共同行,并删除重复项。

【讨论】:

  • 哇,这比我预期的要容易得多。这成功了。
  • 只是为了好玩,我对上述查询以及其他答案的连接版本进行了性能比较。 (添加了几千行数据。)完全没有索引,GROUP BY 查询是最好的查询。使用适当的索引 INTERSECT 优于其他两个。但是,我这里没有使用 Postgresql。
【解决方案2】:

这对你有用吗:

select
    d.id
from
    (select distinct id from the_table where Drivers is not null) as d
    inner join (select distinct id from the_table where Brands is not null) as b
        on b.id=d.id;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-09-08
    • 1970-01-01
    • 2015-08-05
    • 1970-01-01
    • 2022-07-06
    • 2021-12-21
    • 2015-09-08
    相关资源
    最近更新 更多