mysql从同一结果行获取不同数组的列

dohp0rv5  于 2021-06-17  发布在  Mysql
关注(0)|答案(1)|浏览(345)

假设我有一个事件表,我想得到某一天的所有事件(例如2018-01-02)

|   e1    |     d1     |   e2    |     d2     |   e3    |     d3     |
----------------------------------------------------------------------
| event A | 2018-01-01 | event B | 2018-01-02 | event C | 2018-01-02 |
| event D | 2018-01-01 | NULL    | NULL       | NULL    | NULL       |
| NULL    | NULL       | event E | 2018-01-02 | event F | 2018-01-03 |

问题是当我尝试获取这样的结果时:

"SELECT * FROM table WHERE d1='2018-01-02' OR d2='2018-01-02' OR d3='2018-01-02' "

我得到了整行结果(在本例中是三行)。但是我想得到一个单独的结果数组,包含事件和日期。这样地:

Array
(
    [0] => Array
        (
            event => event B
            date => 2018-01-02
        )
    [1] => Array
        (
            event => event C
            date => 2018-01-02
        )
)

到目前为止,我是这样做的,执行了3个查询并加入了它们的结果:

$Sql=$conn->prepare("SELECT e1 AS event, d1 AS date FROM table WHERE d1='2018-01-02'");
$Sql->execute();
$Arr1 = $Sql->fetchAll(PDO::FETCH_ASSOC);

$Sql=$conn->prepare("SELECT e2 AS event, d2 AS date FROM table WHERE d2='2018-01-02'");
$Sql->execute();
$Arr2 = $Sql->fetchAll(PDO::FETCH_ASSOC);

$Sql=$conn->prepare("SELECT e3 AS event, d3 AS date FROM table WHERE d3='2018-01-02'");
$Sql->execute();
$Arr3 = $Sql->fetchAll(PDO::FETCH_ASSOC);

$Arr=array();
foreach($Arr1 AS $a){
 $Arr[]=array($a['event'],$a['date']);
}
foreach($Arr2 AS $a){
 $Arr[]=array($a['event'],$a['date']);
}
foreach($Arr3 AS $a){
 $Arr[]=array($a['event'],$a['date']);
}

print_r($Arr);

但我相信应该有更合适的方法来做到这一点。通过修改sql或php。提前谢谢。

nhhxz33t

nhhxz33t1#

看看https://dev.mysql.com/doc/refman/5.7/en/union.html 试试这个

$Sql=$conn->prepare("(SELECT e1 AS event, d1 AS date FROM table WHERE d1='2018-01-02') UNION (SELECT e2 AS event, d2 AS date FROM table WHERE d2='2018-01-02') UNION (SELECT e3 AS event, d3 AS date FROM table WHERE d3='2018-01-02') ");
$Sql->execute();
$Arr = $Sql->fetchAll(PDO::FETCH_ASSOC);

另请注意,日期是一个保留字,所以你可能要写它与回勾。。。不确定,因为我根本不用它们;)

相关问题