图片表
+----------+---------------+---------------+--------------+
| 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_id | comment_user_id | text |
+------------+---------------------------------+
| 1 | 1 | great article |
| 2 | 2 | not bad |
| 3 | 3 | lorem |
+------------+-----------------+---------------+
SQL查询
SELECT
profile_image,
comment_id
FROM comment
LEFT JOIN image ON image_user_id = comment_user_id
WHERE image_status = 'live'
LIMIT 7
以上代码仅在相关image_pending
字段设置为live
时才会读取评论。如果profile_image
为image_status
,我如何更改代码以使其显示为live
?
上面的代码会输出:
array( 'profile_image' => '834098.png', 'comment_id' => 1 )
应输出:
array(
array( 'profile_image' => '834098.png', 'comment_id' => 1 )
array( 'comment_id' => 2 )
array( 'comment_id' => 3 )
)
答案 0 :(得分:1)
你想要这样的东西吗?
SELECT
profile_image,
comment_id
FROM comment
LEFT JOIN image ON image_user_id = comment_user_id AND image_status = 'live'
LIMIT 7
将返回:
PROFILE_IMAGE COMMENT_ID
834098.png 1
(null) 2
(null) 3
当您想要过滤联接条件时,您正在使用where子句中的image_status ='live'过滤结果。
答案 1 :(得分:1)
删除你的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