V
V
Vadim Stepanenko2021-09-14 22:46:57
PHP
Vadim Stepanenko, 2021-09-14 22:46:57

How to write a sql query with a condition?

Hey! There are the following tables:

orders
id
date
type (book or deposit)
status (success, error)

orders_books
id
order_id
book_id
...

orders_deposits
id
order_id
...

is it possible to get records using the sql query using the following algorithm: we go through orders if type == = book, then we take the necessary info from orders_books, if type === deposit, then we take it from orders_deposits?

only a few solutions come to mind:
1. get the necessary orders records and loop through each record and get the necessary information with a separate request
2. get data from 3 tables with three queries and then somehow separately glue orders_books and orders_deposits so that the sorting is either by order_id or by time

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-09-14
@Vadim1899

Schematically:

SELECT orders.column,
       COALESCE(books.column, deposits.column) AS column
FROM orders 
LEFT JOIN books ON orders.type = 'book' AND orders.id = books.order_id
LEFT JOIN deposits ON orders.type = 'deposit' AND orders.id = deposits.order_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question