Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL VIEW with IF statement

i have two tables in mMySQL:

 - news (news_id, news_titel, news_file_id)
 - files (file_id, file_path, file_name)

I would like to create MySQL VIEW with these columns:

- news_view (news_id, news_title, news_file_id, news_file_path)

But, if news_file_id > 0 then, i get the path of file (file_path + file_name) else news_file_path should be 0

How can i do this VIEW?

EDIT

but what if i want to add two more tables :

categories (category_id, category_name)
users(user_id, user_name)

and table news changed to

news (news_id, news_title, news_file_id, news_author_id, news_category_id)

and view should show only posts with specifed news_author_id, news_category_id, but news_file_path like in the original question?

Thanks, Paul.

like image 926
Pablo Kowalczyk Avatar asked Dec 21 '22 14:12

Pablo Kowalczyk


2 Answers

Try below:

 CREATE VIEW news_view  
   as (SELECT news_id, news_titel, news_file_id, 
       IF(news_file_id > 0, CONCAT(file_path, file_name), 0)
           AS news_file_path
       FROM news a LEFT JOIN files b
            ON a.news_file_id= b.file_id
         JOIN categories cat
            ON a.news_category_id = cat.category_id
         JOIN users u
            ON a.news_author_id = u.user_id
      );

Add the where condition as required.

like image 189
Yogendra Singh Avatar answered Dec 28 '22 05:12

Yogendra Singh


Try this, you can use CASE for your condition,

CREATE VIEW myView
AS
SELECT  a.news_id, a.news_title,
        a.news_file_id,
        CASE 
            WHEN news_file_id = 0 THEN 0
            ELSE CONCAT(file_path, file_name)
        END news_file_path
FROM    news a
        LEFT JOIN files b
            ON a.news_file_id = b.file_id
like image 26
John Woo Avatar answered Dec 28 '22 06:12

John Woo