Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/83.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
SQL:联接表中的大小写_Sql_Join_Case - Fatal编程技术网

SQL:联接表中的大小写

SQL:联接表中的大小写,sql,join,case,Sql,Join,Case,我们有三张桌子 用户{id,角色{u id} 职员{user_id} 客户端{user_id} 一对一的关系-用户员工和用户客户 样本数据: , 问题:如何选择这3个表中的数据? 如果users.role_id=4从客户端加入,则从staff加入。我能像这样做吗 我尝试: 但是有错误 错误:连接行2处或附近的语法错误:当4中的users.role_id然后“clients”ELSE“sta 这是你想要的吗 SELECT u.*, (CASE WHEN users.role_id I

我们有三张桌子

用户{id,角色{u id} 职员{user_id} 客户端{user_id} 一对一的关系-用户员工和用户客户

样本数据:

,

问题:如何选择这3个表中的数据? 如果users.role_id=4从客户端加入,则从staff加入。我能像这样做吗

我尝试:

但是有错误

错误:连接行2处或附近的语法错误:当4中的users.role_id然后“clients”ELSE“sta

这是你想要的吗

SELECT u.*,
       (CASE WHEN users.role_id IN (4) THEN 'clients' ELSE 'staff' END) as role
FROM users u
WHERE u."role_id" IN (4);
以上工作。但如果表中有其他列,则可能需要:

select u.*,
       (case when c.user_id is not null then 'client' else 'staff' end)
from users u left join
     clients c
     on u.role_id = 4 and c.user_id = u.id left join
     staff s
     on u.role_id <> 4 and s.user_id = u.id;
这是你想要的吗

SELECT u.*,
       (CASE WHEN users.role_id IN (4) THEN 'clients' ELSE 'staff' END) as role
FROM users u
WHERE u."role_id" IN (4);
以上工作。但如果表中有其他列,则可能需要:

select u.*,
       (case when c.user_id is not null then 'client' else 'staff' end)
from users u left join
     clients c
     on u.role_id = 4 and c.user_id = u.id left join
     staff s
     on u.role_id <> 4 and s.user_id = u.id;

可以使用两个查询,然后使用UNION ALL组合结果:

SELECT
    <columns>
FROM users AS u
INNER JOIN clients AS c
    ON c.user_id = u.id
WHERE u.role_id = 4

UNION ALL

SELECT
    <columns>
FROM users AS u
INNER JOIN staff AS s
    ON s.user_id = u.id
WHERE u.role_id <> 4

可以使用两个查询,然后使用UNION ALL组合结果:

SELECT
    <columns>
FROM users AS u
INNER JOIN clients AS c
    ON c.user_id = u.id
WHERE u.role_id = 4

UNION ALL

SELECT
    <columns>
FROM users AS u
INNER JOIN staff AS s
    ON s.user_id = u.id
WHERE u.role_id <> 4

请提供样本数据和所需结果。@GordonLinoff编辑文章,其中包含样本数据图片供上传使用。请提供样本数据和所需结果。@GordonLinoff编辑文章,其中包含样本数据图片供上传使用。@GordonLinoff编辑文章,其中包含样本数据图片供上传使用