I have three table books and users and orders, so I want to select all books with info orders by used_id.................................
// get all order for user_id
const conn = await Client.connect()
// const sql = 'SELECT * FROM order_books'
const sql = 'SELECT * FROM books INNER JOIN order_books ON users.id = order_books.user_id;'
const result = await conn.query(sql)
conn.release()
return result.rows
books
CREATE TABLE books (
id SERIAL PRIMARY KEY,
title VARCHAR(150),
totalpages integer,
price integer,
author VARCHAR(255),
type VARCHAR(100),
summary text
);
user
CREATE TABLE users (
id SERIAL PRIMARY KEY,
firstName VARCHAR(150),
lastName VARCHAR(150),
email VARCHAR(150) NOT NULL UNIQUE,
phone VARCHAR(150),
password VARCHAR(255)
);
orders
CREATE TABLE order_books (
id SERIAL PRIMARY KEY,
quantity integer NOT NULL,
user_id bigint REFERENCES users(id) NOT NULL,
books_id bigint REFERENCES books(id) NOT NULL,
status VARCHAR(20) NOT NULL
);
use this
const sql = 'SELECT * FROM books
INNER JOIN order_books ON books.id = order_books.books_id
INNER JOIN users ON users.id = order_books.users
order by users.id asc;'
select
b.*, -- i would select only required columns
ob.*,
u.*
from
books b
join order_books ob (ob.books_id = b.id)
join users u on (u.id = ob.user_id)
order by u.id asc
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.