简体   繁体   中英

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 )
)

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM