如果第一个选择不存在,则使SQL查询选择另一个结果?

时间:2016-06-15 07:09:18

标签: mysql sql

我正在尝试使查询始终返回结果。 使用

SELECT art_price, art_header FROM 'signs' WHERE art_number=113

如果113不存在,我希望查询执行

SELECT art_price, art_header FROM 'signs' WHERE art_number=111

我已经尽力使用IFNULL,COALESCE和CASE但是没有让它发挥作用。

我该怎么办?

好像我的php弄乱了@Felix Pemittan为我解决的问题

<?php
include 'dbc.php';
$query = "SELECT 
    art_price, art_header, art_pic, art_row1, art_row2, art_row3, art_row4  
FROM `signs`
WHERE art_number = ?

UNION ALL

SELECT 
    art_price, art_header, art_pic, art_row1, art_row2, art_row3, art_row4 
FROM `signs`
WHERE 
    art_number = 111
    AND NOT EXISTS(
        SELECT 1
        FROM `signs`
        WHERE art_number = ?
    )";


if($stmt = $conn->prepare($query)){
    $stmt->bind_param('s', $_POST['art_number']);
    $stmt->execute();
    $stmt->bind_result($rowPrice, $rowHeader, $rowPic, $rowArt1, $rowArt2, $rowArt3, $rowArt4);


    while($stmt->fetch()){
        ?>

4 个答案:

答案 0 :(得分:1)

试试这个

SELECT art_price, art_header FROM 'signs' WHERE  (art_number=113 or (art_number=111 and 
(SELECT art_price, art_header FROM 'signs' WHERE art_number=113) is  null))

答案 1 :(得分:1)

你想要这个吗?

{{1}}

答案 2 :(得分:0)

您可以使用Sub Insert_Multiple_Rows() Dim CurrentSheet As Object For Each CurrentSheet In ActiveWindow.SelectedSheets CurrentSheet.Range("A28:A50").EntireRow.Insert Next CurrentSheet End Sub 合并这两个查询,然后在第二个查询中添加UNION ALL子句:

NOT EXISTS

答案 3 :(得分:0)

<强>查询:

IF EXISTS(SELECT 1 FROM 'signs' WHERE art_number=113) 
    SELECT art_price, art_header FROM 'signs' WHERE art_number=113 
ELSE 
    SELECT art_price, art_header FROM 'signs' WHERE art_number=111