我已经使用Postgres 9.6在我的应用程序中实现了标记系统。有三个表。
项目
Media media = new Media(ResourceUtil.getInstance().getResource(music.getPath()).toExternalForm());
MediaPlayer player = new MediaPlayer(media);
player.setCycleCount(Integer.MAX_VALUE);
player.setVolume(.5);
player.play();
标签
Table "public.project"
Column | Type | Collation | Nullable | Default
-------------+-----------------------------+-----------+----------+---------------------------------
id | integer | | not null | nextval('tag_id_seq'::regclass)
name | character varying(255) | | not null |
user_id | integer | | |
项目标签
Table "public.tag"
Column | Type | Collation | Nullable | Default
-------------+-----------------------------+-----------+----------+---------------------------------
id | integer | | not null | nextval('tag_id_seq'::regclass)
tag | character varying(255) | | not null |
user_id | integer | | |
is_internal | boolean | | not null | false
现在,我想获取所有项目的列表,并用一列来表示(对于特定标签)是否具有该标签。
所以我希望结果看起来像这样:
Column | Type | Collation | Nullable | Default
------------------+-----------------------------+-----------+----------+-----------------------------------------
id | integer | | not null | nextval('project_tag_id_seq'::regclass)
tag_id | integer | | not null |
project_id | integer | | | |
user_id | integer | | not null |
这是我到目前为止的查询:
id name has_favorite_tag
1 foo true
2 bar false
3 baz false
我知道当select project.*, CASE(XXXX) as has_project_tag
from project p
join (select * from project_tag where tag_id=1) pt on p.id=pt.project_id
的匹配长度大于0时,我想使用CASE为真-但是我该怎么做?
(实际上,项目表中还有许多字段。)
答案 0 :(得分:0)
有一种可能性(未过滤tag_id;如有必要,添加到内部选择中):
select project.*, exists(select * from project_tag where id=project.id) as has_project_tag from project;