简体   繁体   中英

How to use “join” in postgres

I have two table,

  1. authorCollection contains columns: author, key.
  2. book contains columns: key, title, type,....etc.

There are many types for book, I hope to select the type is not 'UNKNOWN' I hope to join these two table as following:

SELECT A.key, A.author,
       I.key, I."Type"
FROM   authorCollection AS A
JOIN   book AS I
ON  A.key = I.key AND I."TYPE" <> 'UNKNOWN';

But the result I get is: there are two column called "key", and author and type. I hope there is just one "key" column for the result, because they are same.

How can I fix this? I try "natural join", but not solved. Thanks.

fixed above

based on this, I need to group by type and author:

SELECT A.key, A.author, I."Type"
FROM authorCollection A JOIN
     book I
     ON  A.key = I.key AND I."TYPE" <> 'UNKNOWN'
GROUP BY A.author, I."Type";

And then I hope to find the author's name who only appear two times in different types book. For example:

author    type
tom        1
tom        2
tom        3
alex       3
alex       3
tony       1
tony       1

The result is tony and alex, their book appears in two different types. tom appears in three types, so it is not a result. How can I write query statement to realize it? THANKS.

Just put the columns you want in the select . You have two that are called KEY :

SELECT A.key, A.author, I."Type"
FROM authorCollection A JOIN
     book I
     ON  A.key = I.key AND I."TYPE" <> 'UNKNOWN';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM