如果第一个查询返回NULL,则从第二个查询返回默认数据

时间:2016-06-15 03:20:32

标签: mysql

我有一个选择查询。如何将我选择哪个选择不存在项的结果设置为0.

这是一个示例表:

Name      Purchase
Vahn      TV
Vahn      SmartPhone
Ashe      SmartPhone
Vlad      TV
Vlad      Notebook
Vlad      SmartPhone

当我在表中选择不存在的值时,我想做什么:

SELECT Purchase FROM example WHERE Name = 'Balthier'

我的预期结果是:

Name       Purchase
Balthier      -

反之亦然

SELECT Name FROM example WHERE Purchase = 'Drone'

我的预期结果是:

Purchase       Name
Drone           -

只能在MySQL查询中使用吗?或者有更好的建议。非常感谢任何帮助。谢谢

注意:

我尝试过IFNULL和COALESCE,但仍然没有运气:(

3 个答案:

答案 0 :(得分:0)

为了获得第一个预期结果,您可以尝试以下查询:\

SELECT 
Name,
Purchase 
FROM example 
WHERE Name = 'Balthier'

UNION 

SELECT 
*
FROM 
( SELECT 'Balthier','-' ) AS t
WHERE FOUND_ROWS() = 0;

为了获得第二个预期结果,请尝试:

SELECT 
Purchase,
Name 
FROM example 
WHERE Purchase = 'Drone'

UNION 

SELECT 
*
FROM 
( SELECT 'Drone','-' ) AS t
WHERE FOUND_ROWS() = 0;

替代方法:(使用NOT EXISTS

SELECT 
Purchase,
Name 
FROM example 
WHERE Purchase = 'Drone'

UNION 

SELECT 
*
FROM 
( SELECT 'Drone','-' ) AS t
  WHERE NOT EXISTS (
        SELECT 
        *
        FROM example 
        WHERE Purchase = 'Drone'
)

SQL FIDDLE DEMO

答案 1 :(得分:0)

<?php
    $name='Balthier';
    $query="SELECT Purchase FROM example WHERE Name = '$name'";
    $result=$db->query($query);
    $row=$db->feth_array($result);

 ?>

 <?php if($row==''){?>
     <table border="1">
       <tr>
         <td>Name</td>
         <td>Purchae</td>
      </tr>
      <tr>
         <td><?php echo $name;?></td>
         <td>-</td>
      </tr>
    </table>
<?php }?>

如果你使用的是php,那么你也可以像这样显示你的结果。

答案 2 :(得分:0)

你想要这个吗?

select coalesce(Name, 'Balthier') as Name, coalesce(Purchase, '-') as Purchase
from (select 1) t
left join example a
on a.Name = 'Balthier'

SQLFiddle DEMO HERE

反之亦然

select coalesce(Purchase, 'Drone') as Purchase, coalesce(Name, '-') as Name
from (select 1) t
left join example a
on a.Purchase = 'Drone'

SQLFiddle DEMO HERE