如何在Mysql中选择if if语句

时间:2016-07-01 04:03:09

标签: mysql sql

示例数据:

[{url: bing.com},
{url: bing.com/search?q=test}, 
{url: bing.com/efesdf+sdsdksd}]

我想在'之前返回所有网址字符串?'或者' +',这意味着它将返回bing.com/search for 2nd url和bing.com/efesdf for 3rd,删除任何'?'或者' +'

因此我尝试了以下代码

SELECT substring(url,1,instr(pattern,'?')-1) FROM testTable;

然而,在没有'?'将显示为"",是否可以执行if语句,如

if (url.includes('?')){
SELECT substring(url,1,instr(url,'?')-1)
}
else if (url.includes('+')){
SELECT substring(url,1,instr(url,'+')-1)}
}  
else{
SELECT URL
}
FROM testTable;

如果我想选择*并仅更改网址,该怎么办?

请协助, 感谢。

3 个答案:

答案 0 :(得分:1)

也许你需要这个;)

SELECT
    *,
    CASE WHEN LOCATE('?', url) THEN LEFT(url, LOCATE('?', url) - 1)
    WHEN LOCATE('+', url) THEN LEFT(url, LOCATE('+', url) -1)
    ELSE url END AS editedUrl
FROM testTable;

检查SQLFiddle DEMO HERE

答案 1 :(得分:0)

你需要这个? Detail

select id, 
        (
        CASE 
            WHEN qty_1 <= '23' THEN price
            WHEN '23' > qty_1 && qty_2 <= '23' THEN price_2
            WHEN '23' > qty_2 && qty_3 <= '23' THEN price_3
            WHEN '23' > qty_3 THEN price_4
            ELSE 1
        END) AS total
     from product;

答案 2 :(得分:0)

您可以尝试这样

SELECT CASE 
            WHEN LOCATE('?', url ) > 0 
               THEN SUBSTRING( url, 0, LOCATE('?', url ) -1 )
            WHEN LOCATE('+', url ) > 0
                THEN SUBSTRING( url, 0, LOCATE('?', url ) -1 )
               ELSE url 
       END as url
FROM testTable;