填充来自联接

时间:2016-08-12 14:21:47

标签: node.js postgresql

虽然我知道一些SQL,但我之前从未真正使用过关系数据库,因为我意识到这是一个强大的功能,我试图学习如何在PostgreSQL中实现它。我目前有三个数据库表,我试图连接,它们如下:

comics:  
  id(int)
  issue(int)  
  series(varchar[255])  
  publisher(int)  
  type(int)

publishers:  
  id(int)
  name(varchar[255])
  url(varchar[255])

type:
  id(int)
  name(varchar[255])

在每个表中,ID是主键,并且comics.publisher(对于publishers.id)和comics.type(对于type.id)有一个fkey约束

我有以下查询字符串:

'SELECT * FROM comics JOIN publishers ON (publisher = publishers.id) JOIN comic_types ON (type = comic_types.id);'

哪种方式有效,但它没有达到我的预期,我希望得到以下结果:

id: 1,
issue: 1,
series: 'Civil War',
publisher: 'Marvel',
type: 'single issue'

但我得到的是:

id: 1,
issue, 1,
series: 'Civil War',
publisher: 1,
type: 1,
name: 'Single issue',
url: 'marvel.com'

如果我必须命名我的条目,那么就这样吧但是肯定有办法将publishers.name引入comics.publisher并将type.name引入comics.type?

若有,有人可以告诉我怎么做?

2 个答案:

答案 0 :(得分:2)

我强烈建议您使用表别名并限定所有列名。您应该在SELECT c.*, p.name as publisher_name, ct.name as type_name FROM comics c JOIN publishers p ON c.publisher = p.id JOIN comic_types ct ON c.type = ct.id; 中列出所需的列,以确保没有命名冲突。像这样:

GET FILE="C:\PROGRAM FILES\IBM\SPSS\STATISTICS\23\SAMPLES\ENGLISH\EMPLOYEE DATA.SAV".

/* Original Table */.
CTABLES 
  /VLABELS VARIABLES= gender jobcat DISPLAY=NONE 
    /TABLE gender > jobcat[COUNT COLPCT ROWPCT]
      /CATEGORIES VARIABLES=gender jobcat EMPTY=EXCLUDE.

/* Solution 1: Dirty hack, insert granular level variable far left. Force repeat row labels however generate redundant column in output table */.
CTABLES 
  /VLABELS VARIABLES= gender jobcat DISPLAY=NONE 
    /TABLE gender > jobcat [COUNT COLPCT ROWPCT]
      /CATEGORIES VARIABLES=gender jobcat EMPTY=EXCLUDE.



/* Solution 2: Create a single new variable with all combination of categories but again this may not help you derive the correct percentage scores */.
COMPUTE GenJob=sum((Gender="m")*10, JobCat).
VALUE LABELS GenJob
 1 "Female - Clerical"
 2 "Female - Custodial"
 3 "Male - Manager"
 11 "Male - Clerical"
 12 "Male - Custodial"
 13 "Male - Manager".

CTABLES 
  /VLABELS VARIABLES= GenJob DISPLAY=NONE 
    /TABLE GenJob [COUNT COLPCT ROWPCT]
      /CATEGORIES VARIABLES=GenJob EMPTY=EXCLUDE.

答案 1 :(得分:1)

看起来您可能在相同的列名之间发生冲突。明确指定您感兴趣的列。

'SELECT comics.id, comics.issue, comics.series, publishers.name as publisher, type.name as type FROM comics JOIN publishers ON (publisher = publishers.id) JOIN comic_types ON (type = comic_types.id);'