Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/postgresql/10.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-根据其他表的值选择值_Postgresql - Fatal编程技术网

PostgreSQL-根据其他表的值选择值

PostgreSQL-根据其他表的值选择值,postgresql,Postgresql,我有两个表,一个叫做用户,另一个叫做推荐。每个用户都有一个与其关联的代码,这就是他们的外观: USERS TABLE user_id name ref_type other_referral 1 Ely friend SA0987 2 Sandra page 3 Karla friend EC0000 4 Tania email 我想从users表中选择所有内容

我有两个表,一个叫做用户,另一个叫做推荐。每个用户都有一个与其关联的代码,这就是他们的外观:

USERS TABLE

user_id  name    ref_type   other_referral
 1       Ely      friend         SA0987
 2       Sandra   page  
 3       Karla    friend         EC0000
 4       Tania    email 
我想从users表中选择所有内容,但是如果Reference与friend匹配,并且other_Reference不是空的,那么我需要的不是字母数字代码,而是可以从表Reference关联的用户名

例如:

id  name    ref_type    other_referral
1   Ely      friend        Sandra
2   Sandra   page   
3   Karla    friend         Ely
4   Tania    email  
从用户通过转介返回到用户以查找朋友的左侧加入

SELECT u.user_id AS id, u.name, u.ref_type, coalesce(f.name, u.other_referral) AS other_referral
FROM users u
LEFT JOIN referral r
  ON u.ref_type = 'friend'
    AND u.other_referral = r.code
LEFT JOIN users f
  ON r.user_id = f.user_id
ORDER BY id;
我已经通过coalesce为字母数字代码添加了一个后备方案,以防没有朋友使用该代码,或者有不同的ref_类型也可以使用代码


这就是我需要的。

这正是我需要的,谢谢你的帮助!!:
SELECT u.user_id AS id, u.name, u.ref_type, coalesce(f.name, u.other_referral) AS other_referral
FROM users u
LEFT JOIN referral r
  ON u.ref_type = 'friend'
    AND u.other_referral = r.code
LEFT JOIN users f
  ON r.user_id = f.user_id
ORDER BY id;