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

标签 php mysql join

图像表

+----------+---------------+---------------+--------------+
| 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 时读取评论。当 image_statuslive 时,如何更改代码以使其读取 profile_image

上面的代码会输出:

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

最佳答案

你想要这样的东西吗?

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

sqlfiddle demo

当您想过滤连接条件时,您在 where 子句中使用 image_status = 'live' 过滤结果。

关于php - Mysql:当加入字段等于条件时选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19863543/

相关文章:

php - 编译 php-cpp main.cpp 文件时忽略类型属性或对 phpExtension 错误的 undefined reference

php - 使用 PHP 的 cURL lib 中的 POST 不发送

c# - NHibernate - 如何映射 dictionary<value, object>?

ruby-on-rails - 生成迁移-创建连接表

sql - MySQL:按 LIKE 连接两个表

mysql - SQL从多个表中选择值恰好为2

php - 是否可以使用 jquery 添加从 mysql 中获取的数字?

php - 自动同步 Laravel 中的相关表

java - 将这个简单的 C# MySQL 代码转换为 Java

mysql 复合索引我应该使用它们吗