V
V
Vladimir Golub2018-03-30 14:54:10
PostgreSQL
Vladimir Golub, 2018-03-30 14:54:10

How, depending on the value of the author's type attribute, to select a name from different tables (WHEN, CASE)?

There is a view in which I display the id, the author's name and the text of the message.
In the table with messages, I entered the author's id and author's type attributes.
How to get name values ​​from different tables depending on the different type of author.

SELECT 
messages.id
messages.text
    case messages.typeauthor	
      when '1'
      
      when '2'
      
 FROM messages

Author id value
messages.authorid
In the first case, you need to make such a request
SELECT idmc.name
FROM idmc
WHERE idmc.id = messages.authorid

In the second
SELECT suppliers.name
FROM suppliers
WHERE suppliers.id = messages.authorid

Answer the question

In order to leave comments, you need to log in

1 answer(s)
0
0xD34F, 2018-03-30
@RazerVG

SELECT
  m.id,
  m.text,
  CASE m.typeauthor
    WHEN '1' THEN
      (SELECT name FROM idmc WHERE id = m.authorid)
    WHEN '2' THEN
      (SELECT name FROM suppliers WHERE id = m.authorid)
  END
FROM messages m

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question