使用带有空n:n关系的DISTINCT ON

时间:2014-09-26 10:38:07

标签: sql postgresql relationship distinct-on

我是PostgreSQL的新用户,试图使用DISTINCT ON,但我无法实现目标。

以下是我的数据库的简要草图:

  • 带版本控制的文件
  • 带模型的字段(用于表单生成)
  • 文件版本和字段之间的
  • n:n关系

enter image description here

我想为指定文件的版本检索一整套字段。
我的问题是我们可以(并且我们将)空值,即。 缺少FileVersion_Field关系。我会试着给你一个例子:

FileVersion                            Field                                
+----------------+---------+---------+ +----------+-------+---------------+ 
| id_fileversion | id_file | version | | id_field | value | id_fieldmodel | 
+----------------+---------+---------+ +----------+-------+---------------+ 
| 1              | 1       | 1       | | 1        | Smith | 1             | 
| 2              | 1       | 2       | | 2        | 20    | 2             | 
+----------------+---------+---------+ | 3        | 25    | 2             | 
                                       +----------+-------+---------------+

FileVersion_Field             FieldModel
+----------------+----------+ +---------------+------+
| id_fileversion | id_field | | id_fieldmodel | type |
+----------------+----------+ +---------------+------+
| 1              | 1        | | 1             | Name |
| 1              | 2        | | 2             | Age  |
| 2              | 3        | +---------------+------+
+----------------+----------+ 

在这个例子中,我想得到这些结果:

-- id_file=1 & version=1
Name | Smith
Age  | 20
-- id_file=1 & version=2
Name | 
Age  | 25

这是我尝试过的,但不起作用:

SELECT DISTINCT ON(FieldModel.id_fieldmodel) *
FROM File
LEFT JOIN FileVersion ON File.id_file = FileVersion.id_file
LEFT JOIN File_Field ON FileVersion.id_fileversion = File_Field.id_fileversion
LEFT JOIN Field ON File_Field.id_field = Field.id_file
RIGHT JOIN FieldModel ON (Field.id_fieldmodel = FieldModel.id_fieldmodel OR FieldModel.id_fieldmodel IS NULL)
WHERE (FieldModel.id_fieldmodel IS NOT NULL AND FileVersion.version = 2 AND File.id_file = 1)
   OR (File.id_fieldmodel IS NULL)
ORDER BY FieldModel.id_fieldmodel

0 个答案:

没有答案