如何使用Postgres执行以下查询?

时间:2015-03-02 22:24:55

标签: sql postgresql

这是示例

banzai=# select letter_id, length_id, word from words;
 letter_id | length_id | word  
-----------+-----------+-------
         1 |         1 | run
         3 |         1 | tea
         2 |         1 | cat
         2 |         2 | cast
         2 |         3 | coast
         1 |         3 | roast
         1 |         2 | rest
         3 |         2 | team
         3 |         3 | toast
(9 rows)

banzai=# select letter from letters;
 letter 
--------
 R
 C
 T
(3 rows)


banzai=# select length from lengths;
 length 
--------
      4
      5
      3
(3 rows)

banzai=# select length, letter, word from words, lengths, letters where words.length_id = lengths.id and words.letter_id = letters.id;
 length | letter | word  
--------+--------+-------
      3 | C      | cat
      3 | R      | run
      3 | T      | tea
      4 | R      | rest
      4 | C      | cast
      4 | T      | team
      5 | R      | roast
      5 | C      | coast
      5 | T      | toast
(9 rows)

我想在HTML中生成以下表格

       R       T       C
3     run     tea      cat
4     rest    team     cast
5     roast   toast    coast

我的java(后端)代码中有一个方法可以在json中生成数据。 Angularjs(前端)将获取json并在html中显示表

1 个答案:

答案 0 :(得分:3)

如果你想要JSON,这将返回一个对象:

select json_object_agg(length, o)
from (
    select length, json_object_agg(letter, word) as o
    from
        words w
        inner join
        lengths l on w.length_id = l.id
        inner join
        letters t on w.letter_id = t.id
    group by length
) s;
                                                                        json_object_agg                                                                         
----------------------------------------------------------------------------------------------------------------------------------------------------------------
 { "4" : { "R" : "rest", "C" : "cast", "T" : "team" }, "5" : { "R" : "roast", "C" : "coast", "T" : "toast" }, "3" : { "C" : "cat", "R" : "run", "T" : "tea" } }

以上查询适用于9.4。在9.3中,它有点困难,但也可以这样做。