如果条件为真,则运行MySQL查询,否则运行另一个查询

时间:2019-04-04 12:56:39

标签: mysql sql

我需要将地址列拆分为streetName和streetNumber。问题有时是位于streetName列中的完整地址,有时也位于streetNumber列中。我正在使用此代码进行拆分     replace(streetName, substring_index(streetName, ' ', -1), '') as street,substring_index(streetName, ' ', -1) as number

和     replace(streetNumber, substring_index(streetNumber, ' ', -1), '') as street,substring_index(streetNumber, ' ', -1) as number.

如果streetName为null或为空,则我要执行选择查询语句的这一部分,然后使用streetNumber执行代码,反之亦然。

我必须在存储过程中区分ifStreet()和IfStreetNumber()。但是我在运行它时遇到错误,并且如果我直接将代码放在case语句中,它也无法正常工作。我收到一条错误消息,说明您的SQL语法有错误。是否可以根据条件运行查询,或者我的方法有什么问题?谢谢

  SELECT 
    firstName,
    lastName,
    D.email AS email,
    streetName,
    streetNumber,
    zipCode,
    city,
    IF(length(zipCode) =5,'Germany','') As country,
    registeredOn,
    N.email AS matchedEmail,
     CASE
        WHEN gender = 'Frau' OR gender = 'f' THEN 'f'
        WHEN gender = 'Herr' OR gender = 'm' THEN 'm'
        ELSE ''
    END AS Title,
    CASE
        WHEN gender = 'Frau' OR gender = 'f' THEN 'Frau'
        WHEN gender = 'Herr' OR gender = 'm' THEN 'Herr'
        ELSE ''
    END AS Salutation,
    CASE
        WHEN streetName !='' THEN 
          call ifStreet()
    ELSE 
           call ifStreetNumber()
    END

FROM
    matchFiles.TableA AS D
        INNER JOIN
    matchFiles.TableB AS N ON D.email = N.email
WHERE
    registeredOn <= '2018-08-31';

2 个答案:

答案 0 :(得分:0)

SELECT语句中不允许

存储过程。因此,您的方法将行不通。

尝试将逻辑从存储过程转换为适当的子查询。

答案 1 :(得分:0)

我重组了查询,并使用存储过程删除了该查询。我使用IFNULL函数来进行替换以使用streetName或streetNumber,这取决于哪一列具有完整的地址字符串。

replace(IFNULL(streetName,streetNumber), substring_index(IFNULL(streetName,streetNumber), ' ', -1), '') as street,substring_index(IFNULL(streetName,streetNumber), ' ', -1) as number