Returns a string instead of a field value when a condition is satisfied in MySQL

With my current saga, to try to do something right in the database instead of using some php logic, another question.

For example: I have a table: m/ id | by | msg m/ id | by | msg m/ id | by | msg identifier, who did it and what is the message. The by field is an integer associated with another table in which the name is stored. Normally I would leave a join with two tables:

 SELECT m.id, m.msg, user.name FROM m LEFT JOIN user ON m.by = u.id 

With the resulting ratio, for example:

 1 | Hello World | Richard 2 | Foo Bar | Some else 3 | Howdy | Richard 

I am rich and have user.id=4

Is it possible for the resulting relationship to be displayed to you instead of Richard , where the condition user.id = (int) is satisfied?

+4
source share
2 answers
 SELECT m.id, m.msg, IF(user.id = 4, 'you', user.name) AS name FROM m LEFT JOIN user ON m.by = user.id 
+4
source

Do it like this:

 SELECT m.id, m.msg, (case when user.id = 4 then 'You' else user.name end) as username FROM m LEFT JOIN user ON m.by = u.id 
+3
source

Source: https://habr.com/ru/post/1413021/


All Articles