简体   繁体   English

Mysql:选择加入字段等于条件时

[英]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 SQL查询

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 . 上面的代码仅在相关的image_pending字段设置为live时读取注释。 How could I change the code to make it read profile_image when the image_status is live ? image_status live时,如何更改代码以使其读取profile_image

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 sqlfiddle演示

You were filtering the result using image_status = 'live' in the where clause, when you want to filter the join condition instead. 当您想过滤联接条件时,您在where子句中使用image_status ='live'过滤了结果。

Remove your where clause ans use case to check the status 删除您的where子句和用例以检查状态

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 小提琴

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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