Michael Rich
Michael Rich

Reputation: 301

Mysql: Select When Joined Field Equals Condition

Image Table

+----------+---------------+---------------+--------------+
| image_id | image_user_id | profile_image | image_status |
+----------+---------------+---------------+--------------+
|        1 |             1 |    834098.png |         live |
|        2 |             2 |    347903.jpg |      pending |
|        3 |             3 |    447903.jpg |      pending |
+----------+---------------+---------------+--------------+

Comment Table

+------------+-----------------+---------------+
| comment_id | comment_user_id | text          |
+------------+---------------------------------+
|          1 |               1 | great article |
|          2 |               2 |       not bad |
|          3 |               3 |         lorem |
+------------+-----------------+---------------+

SQL Query

SELECT
    profile_image,
    comment_id
FROM comment
LEFT JOIN image ON image_user_id = comment_user_id
WHERE image_status = 'live'
LIMIT 7

The above code only reads comments when the relating image_pending field is set to live. How could I change the code to make it read profile_image when the image_status is live?

The above code would output:

array( 'profile_image' => '834098.png', 'comment_id' => 1 )

It should output:

array(
    array( 'profile_image' => '834098.png', 'comment_id' => 1 )
    array( 'comment_id' => 2 )
    array( 'comment_id' => 3 )
)

Upvotes: 1

Views: 42

Answers (2)

Filipe Silva
Filipe Silva

Reputation: 21657

Is something like this that you want?

SELECT
    profile_image,
    comment_id
FROM comment
LEFT JOIN image ON image_user_id = comment_user_id AND image_status = 'live'
LIMIT 7

Will return:

PROFILE_IMAGE   COMMENT_ID
834098.png          1
(null)              2
(null)              3

sqlfiddle demo

You were filtering the result using image_status = 'live' in the where clause, when you want to filter the join condition instead.

Upvotes: 1

M Khalid Junaid
M Khalid Junaid

Reputation: 64466

Remove your where clause ans use case to check the status

SELECT
(CASE WHEN image_status = 'live' THEN 
    profile_image ELSE NULL END ) profile_image ,
    comment_id
FROM comment
LEFT JOIN image ON image_user_id = comment_user_id
LIMIT 7

Fiddle

Upvotes: 1

Related Questions