如何在查询中避免条件多个SELECT

时间:2014-10-09 06:36:58

标签: mysql sql

我有这个简单的SQL

SELECT 
(CASE
    WHEN
        (SELECT 
                Name
            FROM
                Customers
            WHERE
                Customers_id = Customer) IS NOT NULL
    THEN
        (SELECT 
                Name
            FROM
                Customers
            WHERE
                Customers_id = Customer)
    ELSE Customer
END) AS Customer,
DateStart,
ProgramsRun.Programs_id,
RunInSeconds,
SwSQL,
SwProgram,
Name AS ProgramName
FROM
ProgramsRun
    LEFT JOIN
Programs ON ProgramsRun.Programs_id = Programs.Programs_id;

我的问题是如何避免制作两个相同的SELECT语句:一个作为条件,另一个作为值选择。我知道我可以创建一个临时变量,但这迫使我使用存储过程或临时表。有一种简单的方法可以避免这种情况吗?

3 个答案:

答案 0 :(得分:0)

试试这个

SELECT 
 IsNull(Name,Customer)
AS Customer,
DateStart,
ProgramsRun.Programs_id,
RunInSeconds,
SwSQL,
SwProgram,
Name AS ProgramName
FROM
ProgramsRun
    LEFT JOIN
Programs ON ProgramsRun.Programs_id = Programs.Programs_id;

答案 1 :(得分:0)

您可以像这样使用IFNULL

IFNULL((SELECT 
                Name
            FROM
                Customers
            WHERE
                Customers_id = Customer),Customer)

COALESCE喜欢这样:

COALESCE((SELECT 
                Name
            FROM
                Customers
            WHERE
                Customers_id = Customer),Customer)

参考:

答案 2 :(得分:0)

您可以使用join

重写查询
SELECT 
COALESCE(c.Name,Customer) AS Customer,
DateStart,
ProgramsRun.Programs_id,
RunInSeconds,
SwSQL,
SwProgram,
Programs.`Name` AS ProgramName
FROM ProgramsRun
LEFT JOIN Programs ON ProgramsRun.Programs_id = Programs.Programs_id
LEFT JOIN Customers c ON c.Customers_id = Customer;