我有这个简单的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语句:一个作为条件,另一个作为值选择。我知道我可以创建一个临时变量,但这迫使我使用存储过程或临时表。有一种简单的方法可以避免这种情况吗?
答案 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;