是否可以从另一个表中的行命名SQL结果列? (Postgres) [英] Is it possible to name SQL result columns from rows in another table? (Postgres)

查看:70
本文介绍了是否可以从另一个表中的行命名SQL结果列? (Postgres)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我的用户具有动态属性表。简化:

Basically I have users with a dynamic attributes table. Simplified:

SELECT * FROM users;
 id  |                  email                   
-----+------------------------------------------
  1 | example@example.com


SELECT * FROM user_attributes;
 id |      name      
----+----------------
  1 | Salutation
  2 | Given Name
  3 | Surname
  4 | Alias
  5 | Address
  6 | Address 2
  7 | Address 3
  8 | City
  9 | Region
....

SELECT * FROM user_attribute_values;
 client_id | attribute_id | value 
-----------+--------------+-------

我要执行的是一个SELECT,该查询将返回列user_id,city,city&区域不为空。

What I'm looking to do is a SELECT that would return columns user_id, city, region where city & region are not empty.

user_attributes表的原因可能是要存储有关用户的任意数量的自定义字段,并且无法事先知道它们将是什么将它们创建为用户表的列。

The reason for the user_attributes table is one may want to store any number of custom fields about the user, and it's impossible to know beforehand what they will be to create them as columns of the user table.

推荐答案

使用 INNER JOIN

SELECT u.id, a_city.value AS city, a_region.value AS region
 FROM users u
 INNER JOIN user_attribute_values a_city ON a_city.client_id = u.id AND a_city.attribute_id = 8
 INNER JOIN user_attribute_values a_region ON a_region.client_id = u.id AND a_region.attribute_id = 9
 WHERE LENGTH(a_city.value) > 0
   AND LENGTH(a_region.value) > 0

这篇关于是否可以从另一个表中的行命名SQL结果列? (Postgres)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆