J
J
jrborisov2016-03-08 22:03:03
MySQL
jrborisov, 2016-03-08 22:03:03

How to make a selection from the database by joining with different tables depending on the value of the field?

there is a table that stores: user id, message id and type message type, depending on the message type, you need to connect the table with another. let's say if the type is "user" then join with the Users table if 'System' then with the Systems table
something like:
SELECT *
FROM tbl_notice
IF (type="user") { JOIN tbl_users ....}
else{JOIN tbl_system.. .}
WHERE id_user=1

Answer the question

In order to leave comments, you need to log in

3 answer(s)
I
Igor, 2016-03-08
@jrborisov

Fields (kolvo and on type) in both tables are identical?
If yes, and splitting the tables is still necessary, then two queries and a union result

A
Alexey, 2016-03-08
@k1lex

I think the essence will be clear - we join the tables with a left join and if the value in the first case is NULL, then we take another value. If there will be more than 2 message types, use the coalesce operator

select 
[ id пользователя]
 ISNULL(U.ID, system.id] as [ID сообщения]
 from tbl_notice  N
left join user  U ON  U.ID=N.[id сообщения] and type="user"
left join Systems  S ON  S.ID=N.[id сообщения] and type="System"

PS Late I saw that the question is for MYSQL, but for MS SQL it will work for sure.

S
Sanan Yuzb, 2016-03-08
@Sanan07

Here

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question