V
V
Vladislav2021-06-08 14:24:58
SQL
Vladislav, 2021-06-08 14:24:58

LEFT JOIN on IF condition?

How to make left join only if parameter is 1:

DROP PROCEDURE IF EXISTS get_artist;
CREATE PROCEDURE get_artist(IN artist_id integer(11), IN show_links integer(1))
BEGIN
    SELECT * FROM artist where id = artist_id;
    IF show_links=1
        THEN LEFT JOIN artist_social_links ON artist_social_links.artist_id = artist_id;
    END IF;
end;
CALL get_artist(196796, 1);


Here is my gk but it does not work, tell me how to implement it correctly

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Akina, 2021-06-08
@cr1gger

DROP PROCEDURE IF EXISTS get_artist;
DELIMITER ;;
CREATE PROCEDURE get_artist(IN artist_id integer(11), IN show_links integer(1))
BEGIN
    CASE WHEN show_links=1
         THEN 
             SELECT * 
             FROM artist 
             where id = artist_id;
         ELSE  
             SELECT * 
             FROM artist 
             LEFT JOIN artist_social_links ON artist_social_links.artist_id = artist_id 
             where id = artist_id ;
    END CASE;
END;;
DELIMITER ;
CALL get_artist(196796, 1);

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question