postgresql - postgresql 和子查询作为列(重复行)
问题描述
我在使用子查询作为列的 postgresql 查询时遇到了一些问题。我不是 DBA,因为我通常依靠 ORM 来处理我的数据库内容,所以请耐心等待.....这是我的缩写表定义:
\d profile
Table "public.profile"
Column | Type | Modifiers
---------------------------+--------------------------+------------------------------------------------------
id | integer | not null default nextval('profile_id_seq'::regclass)
_tracking_number_obj_id | integer
\d trackingnumber;
Table "public.trackingnumber"
Column | Type | Modifiers
-----------------+-----------------------+-------------------------------------------------------------
id | integer | not null default nextval('trackingnumber_id_seq'::regclass)
tracking_number | character varying(16) | not null
\d dd;
Table "public.dd"
Column | Type | Modifiers
----------------+-----------------------+-----------------------------------------------------------
id | integer | not null default nextval('dd_id_seq'::regclass)
created_date | date | not null
completed | boolean | not null
completed_date | date |
type | character varying(10) | not null
profile_id | integer | not null
我正在尝试的查询:
select tn.tracking_number,
last_c,
last_l
from
trackingnumber as tn, profile as p, dd as dd,
(select max(completed_date) from dd as dd, profile as p where profile_id = p.id and type='C') as last_c,
(select max(completed_date) from dd as dd, profile as p where profile_id = p.id and type='L') last_l
where p._tracking_number_obj_id = tn.id and dd.profile_id = p.id;
预期结果将是每个 p.id 一行,但我为 dd 表中的每一行得到一行。
例子:
select count(*) from dd;
count
-------
10
上述查询的结果:
tracking_number | last_c | last_l
-----------------+--------------+--------------
5004 | (2019-10-23) | (2019-10-23)
5004 | (2019-10-23) | (2019-10-23)
5004 | (2019-10-23) | (2019-10-23)
5004 | (2019-10-23) | (2019-10-23)
5004 | (2019-10-23) | (2019-10-23)
5004 | (2019-10-23) | (2019-10-23)
5004 | (2019-10-23) | (2019-10-23)
5003 | (2019-10-23) | (2019-10-23)
5003 | (2019-10-23) | (2019-10-23)
5003 | (2019-10-23) | (2019-10-23)
期望的结果是:
tracking_number | last_c | last_l
-----------------+--------------+--------------
5004 | (2019-10-23) | (2019-10-23)
5003 | (2019-10-23) | (2019-10-23)
解决方案
看起来加入dd
是不必要的。
尝试删除
dd as dd,
和
and dd.profile_id = p.id
从查询中查看您是否更喜欢结果。
推荐阅读
- google-cloud-platform - Beam SQL / Apache Beam 在运行多个连接时速度较慢
- javascript - 在从键盘输入期间每 n 个字符后加上破折号并编辑确切数字
- r - R REGEX 匹配 - 至少 1 个小写字母、1 个数字,并且没有 8 个长度的特殊字符
- sql-server-2012 - 分组计数的运行总计
- node.js - Express JS Web 应用程序上的用户登录和身份验证
- python - Python/Tkinter - 将按钮状态写入文件以在下次启动时自动重新应用?
- javascript - 通过 JavaScript 分配 div 的宽度和高度时,边框不工作?
- git - git给出关于在cmd中运行vim的错误
- javascript - 任何人都可以解释 node.js 中的请求库吗?
- php - 重写路由关闭 301 重定向到 Laravel 中的控制器