我有这样的查询:
SELECT Name,
REPLACE(RTRIM((
SELECT CAST(Score AS VARCHAR(MAX)) + ' '
FROM
(SELECT Name, Score
FROM table
WHERE
---CONDITIONS---
) AS InnerTable
WHERE (InnerTable.Name = OuterTable.Name) FOR XML PATH (''))),' ',', ') AS Scores
FROM table AS OuterTable
WHERE
---CONDITIONS---
GROUP BY Name;
可以看出,我使用相同的一组条件来推导InnerTable
和OuterTable
。有没有办法缩短这个查询?我问这个是因为,有时回来,我在MySQL中看到了一个关键字USING
,它简化了我的生活,使用它可以指定一次查询,然后在查询的其余部分使用别名。
答案 0 :(得分:3)
您可以查看创建公用表表达式(CTE)。这是对选择别名的最佳选择。不幸的是,我不确定它会使你的查询有多少,但它确实阻止你定义两次where条件。见下文:
with temp as
(
SELECT Name, Score
FROM table
WHERE whatever = 'whatever'
)
SELECT Name,
REPLACE(RTRIM((
SELECT CAST(Score AS VARCHAR(MAX)) + ' '
FROM
(SELECT Name, Score
FROM temp ) AS InnerTable
WHERE (InnerTable.Name = OuterTable.Name) FOR XML PATH (''))),' ',', ') AS Scores
FROM temp AS OuterTable
GROUP BY Name;