Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/mysql/66.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Php 当没有返回行时,从select查询中获取预定义值_Php_Mysql_Sql - Fatal编程技术网

Php 当没有返回行时,从select查询中获取预定义值

Php 当没有返回行时,从select查询中获取预定义值,php,mysql,sql,Php,Mysql,Sql,我的问题是: SELECT col1, col2, sum(col3), ref FROM tbl1 LEFT JOIN tbl2 on tbl2.ref = tbl1.ref WHERE ref in (1,2,3,4,5,...); PHP中的结果如下所示: [ 0 => [ 'col1' => 'x', 'col2' => 'y', 'col3' => 1234, 'ref' =&

我的问题是:

SELECT 
    col1, col2, sum(col3), ref
FROM tbl1
LEFT JOIN tbl2 on tbl2.ref = tbl1.ref
WHERE ref in (1,2,3,4,5,...);
PHP中的结果如下所示:

[
    0 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 1234,
        'ref'  => 1,
    ],
    1 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 1234,
        'ref'  => 3,
    ],
    2 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 1234,
        'ref'  => 3,
    ],
    3 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 1234,
        'ref'  => 5,
    ],
]
由于tbl中没有参考文献2和4的数据,因此仅返回了1,3,5

但是如果没有找到那些
ref
中的行,我需要一些默认数据(至少一行)

比如:

[
    0 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 'z',
        'ref'  => 1,
    ],
    1 => [
        'col1' => null,
        'col2' => null,
        'col3' => null,
        'ref'  => 2,
    ],
    2 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 1234,
        'ref'  => 3,
    ],
    3 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 1234,
        'ref'  => 3,
    ],
    4 => [
        'col1' => null,
        'col2' => null,
        'col3' => null,
        'ref'  => 4,
    ],
    5 => [
        'col1' => 'x',
        'col2' => 'y',
        'col3' => 1234,
        'ref'  => 5,
    ],
]

这可能吗?

您可以使用这些值创建一个派生表,并使用
连接:

SELECT tbl.col1, tbl.col2, tbl.col3, r.ref
FROM (SELECT 1 as ref UNION ALL
      SELECT 2 as ref UNION ALL
      SELECT 3 as ref UNION ALL
      SELECT 4 as ref UNION ALL
      SELECT 5 as ref
     ) r LEFT JOIN
     tbl
     ON r.ref = tbl.ref;

实际上,这个列表不仅是(1,2,3,4,5),它应该是(1,2,3,…)@Amin。只需扩展表中的值。