2016-06-15 73 views
0

我試圖做一個查詢總是返回一個結果。 使用如果第一個選擇不存在,使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()){ 
 
     ?>

+0

這兩個sql總是會給你一個記錄還是沒有? – Blank

回答

0

可以使用UNION ALL結合這兩個查詢,然後添加一個NOT EXISTS子句的第二個查詢:

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

UNION ALL 

SELECT 
    art_price, art_header 
FROM `signs` 
WHERE 
    art_number = 111 
    AND NOT EXISTS(
     SELECT 1 
     FROM `signs` 
     WHERE art_number = 113 
    ) 
+0

給我一個錯誤:( –

+0

@PetrusAlli什麼錯誤? –

+0

1064 - 你的SQL語法有錯誤;檢查與您的MariaDB服務器版本相對應的手冊,以在''符號'附近使用正確的語法WHERE art_number = 113 UNION ALL SELECT art_price,art_header F'at line 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 
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)) 
+0

#1064 - 你的SQL語法錯誤;檢查與您的MariaDB服務器版本相對應的手冊,以在''符號'附近使用正確的語法'WHERE art_number = 113 UNION ALL SELECT art_price,art_header F'at line 3 –

1

你想要嗎?

SELECT art_price, art_header 
FROM `signs` 
WHERE art_number in (113, 111) 
ORDER BY art_number DESC 
LIMIT 1 
相關問題