Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/9.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如果第二个表中存在数据,则使用标志连接来自两个postgresql表的数据_Sql_Postgresql_Join - Fatal编程技术网

如果第二个表中存在数据,则使用标志连接来自两个postgresql表的数据

如果第二个表中存在数据,则使用标志连接来自两个postgresql表的数据,sql,postgresql,join,Sql,Postgresql,Join,我有两张桌子。tools表存储了用户可以在我们的网站上启用的所有可用工具的列表 user\u tools表记录每个用户安装的工具。 例如,如果具有user\u id13的用户安装了具有tool\u id'mailchimp'的工具,这将在user\u tools表中创建一个新行,其中包含user\u id13和tool\u id'mailchimp' 我们的网站上有一个页面,显示所有工具,其中一个部分显示当前安装的工具,另一个部分显示尚未安装的工具 我想编写一个SQL查询来填充此页面。查询

我有两张桌子。
tools
表存储了用户可以在我们的网站上启用的所有可用工具的列表

user\u tools
表记录每个用户安装的工具。

例如,如果具有
user\u id
13
的用户安装了具有
tool\u id
'mailchimp'
的工具,这将在user\u tools表中创建一个新行,其中包含
user\u id
13
tool\u id
'mailchimp'

我们的网站上有一个页面,显示所有工具,其中一个部分显示当前安装的工具,另一个部分显示尚未安装的工具

我想编写一个SQL查询来填充此页面。查询必须获取所有工具,并包含一个名为
installed
的布尔列,如果用户安装了此工具,则该列为true。我该怎么做

我想我需要一个
外部联接
,也许有一个
子句存在
,但无法找到它


干杯。

您可以使用
左加入
如下:

SELECT
    t.*,
    CASE WHEN u.tool_id IS NULL THEN 0 ELSE 1 END installed 
FROM 
    tools t
    LEFT JOIN user_tools u ON t.tool_id = t.tool_id AND u.user_id = ?
这将返回所有工具,并带有
installed
标志,指示是否已为当前用户安装了每个工具


问号应替换为当前正在浏览您网站的用户的id

您可以使用
存在
不存在
。对于已安装的工具:

select t.*
from tools t
where exists (select 1
              from user_tools ut
              where ut.tool_id = t.tool_id and
                    ut.user_id = ?
             );
对于未安装的工具,将
存在
替换为
不存在

如果希望将其作为单个结果集,则可以使用相关子查询:

select t.*,
       ( exists (select 1
                 from user_tools ut
                 where ut.tool_id = t.tool_id and
                       ut.user_id = ?
                )
       ) as user_has_tool
from tools t
where