简体   繁体   中英

How to get data by using different column values refrencing same table

I have two tables:

create table 
books (
       id int
      ,bookname text
      );

create table 
users(
      id int
     ,name text
     ,book_1 int
     ,book_2 int
     ,book_3 int
     );

Now, 'book_1', 'book_2', 'book_3' contains id of table 'books'.

I am trying to create a single query using join to get the all three book names with user name.

I am able to get one book name, but how will I get all the three books name?

SELECT user.name
      ,books.name 
FROM user LEFT JOIN books ON books.id=user.book_1; 

(This is giving me one book detail)

Using PostgreSQL.

I want result in one row. like

username, book_1_name, book_2_name, book_3_name 

Don't want multiple rows.

You can use sub-selects to get bookname of each username in a single row ( if id in table books is unique )

select name username
      ,(select bookname from books where id=book_1) book1_name
      ,(select bookname from books where id=book_2) book2_name
      ,(select bookname from books where id=book_3) book3_name
from users

> SQLFIDDLE DEMO

SELECT user.name
      ,books.name
FROM user LEFT JOIN books ON books.id=user.book_1
          OR books.id=user.book_2 
          OR books.id=user.book_3; 

join on all id's

This may help you

SELECT user.name
      ,books.name 
FROM user LEFT JOIN books ON books.id in (select id from  books)

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