php - MySQL选择一行中的多行

标签 php mysql sql

我想要这样的东西,但不确定我的语法是否正确。 我将使用 php 执行此操作。

SELECT 
    a.column1,
    a.column2,
    b.column1,
    c.column1,
    IF a.column3 NOT NULL
        THEN (
            SELECT c.column1, c.column2, c.column3, d.column1
            FROM table_d d
            INNER JOIN table_c c
                ON d.column1 = c.column1 AND c.column4 = 1
            WHERE d.column2 = a.column3
        );
    END IF;

FROM table_a a

    INNER JOIN table_b b
        ON a.column1 = b.column1 AND b.column2 = 1

    INNER JOIN table_c c
        ON a.column1 = c.column1 AND c.column2 = 1

WHERE
    a.column1 = 1000
    AND b.column3 = 1
    AND c.column3 = 0

ORDER BY 
        a.column1 ASC

所以输出将是这样的:

如果它有多行且前几列的数据相同就可以了。像这样:

灰色区域来自outer SELECT,白色区域来自inner SELECT

注意外层和内层select语句都有table_c。如果没有 IF 语句,我可以这样做吗?

SELECT 
    a.column1,
    a.column2,
    b.column1,
    c.column1,
    cc.column1,
    cc.column2,
    cc.column3,
    d.column1   

FROM table_a a

    INNER JOIN table_b b
        ON a.column1 = b.column1 AND b.column2 = 1

    INNER JOIN table_c c
        ON a.column1 = c.column1 AND c.column2 = 1

    LEFT JOIN table_d d
        ON  a.column3 = d.column2

    INNER JOIN table_c cc
        ON d.column1 = cc.column1 AND cc.column4 = 1

WHERE
    a.column1 = 1000
    AND b.column3 = 1
    AND c.column3 = 0

ORDER BY 
        a.column1 ASC

我觉得有点不对劲。 如果我使用 fetch_assoc 会怎样? 甚至可以在一个查询中执行此操作吗?

最佳答案

尝试这样的事情:

SELECT 
    a.column1,
    a.column2,
    b.column1,
    c.column1,
    IF (a.column3 NOT NULL,c_2.column1,''),
    IF (a.column3 NOT NULL,c_2.column2,''),
    IF (a.column3 NOT NULL,c_2.column3,''),
    IF (a.column3 NOT NULL,d.column4,'')

FROM table_a a

    INNER JOIN table_b b
        ON a.column1 = b.column1 AND b.column2 = 1

    INNER JOIN table_c c
        ON a.column1 = c.column1 AND c.column2 = 1

    INNER JOIN table_c as c_2
        ON d.column1 = c.column1 AND c.column4 = 1

    INNER JOIN table_d 
        ON a.column1 = c.column1 AND c.column2 = 1
WHERE
    a.column1 = 1000
    AND b.column3 = 1
    AND c.column3 = 0
ORDER BY 
        a.column1 ASC

关于php - MySQL选择一行中的多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31670310/

相关文章:

php preg_replace 字符串提取

php - 我可以在 PHP 中混合使用 MySQL API 吗?

python - 减少应用程序和数据库的 I/O

mysql - where 子句中的数字如何影响子查询

c# - 执行存储过程并通过输出和 sql 参数将行计数返回给代码

php - 如何在我的数据库中存储 $_SESSION 值

php - 为现有网站开发移动应用程序(Iphone、Blackberry、Android)

php - 在android中使用php从mysql数据库获取数据

sql - 一条语句中的多个游标

mysql - 返回 MySQL 中 MAX 函数的相应列