我需要一个小查询的帮助。
表A: - 状态及其内容如下。
status_id status_descrip
1 held
2 release
3 WIP
表B: - 条目是另一个有30个字段的表。其中2个字段指的是表A->状态表。为简单起见,我正在跳过其他字段并仅记下与状态相关的字段。
entry_id design_status stress_status
1 3 1
2 1 2
3 NULL 2
4 3 3
5 NULL 1
6 NULL NULL
7 NULL 2
我无法将Entry的结构更改为分为2个表,一个作为design_status,另一个作为stress_status。
现在我希望条目表中的条目将状态替换为其描述。所以输出将是
entry_id design_status_descrip stress_status_descrip
1 WIP held
2 held release
3 NULL release
4 WIP WIP.
5 NULL held
6 NULL NULL
7 NULL release
提前致谢!
编辑: -
使用条目编辑问题。
谢谢您的所有回复!
最终为我工作的查询是,
SELECT b.entry_id, design_status_descrip = d.status_descrip,
stress_status_descrip = s.status_descrip FROM entry AS b
LEFT OUTER JOIN status AS d ON b.design_status = d.status_id
LEFT OUTER JOIN status AS s ON b.stress_status = s.status_id
请告诉我,如果我可以改进此查询。
答案 0 :(得分:1)
SELECT
e.entry_id,
s1.status_descrip as design_status_descrip,
s2.status_descrip as stress_status_descrip
FROM entry e, status s1, status s2
WHERE
e.design_status = s1.status_id
AND e.stress_status = s2.status_id
答案 1 :(得分:1)
只需加入两次状态表
From
Entry e
Inner join status ds
On e. design_status_id = ds.status_id
Inner join status ss
On e.stress_status_id = ss.status_id
答案 2 :(得分:1)
最简单的方法是两次加入状态表。假设架构中的design_status和stress_status列具有适当的约束,我使用了INNER JOIN。编辑了变更的要求。
DECLARE @status TABLE
(
status_id INT PRIMARY KEY,
status_descrip VARCHAR(32) NOT NULL UNIQUE
);
INSERT @status SELECT 1,'held' UNION SELECT 2,'release' UNION SELECT 3,'WIP';
DECLARE @b TABLE
(
entry_id INT PRIMARY KEY,
design_status INT,
stress_status INT
);
INSERT @b SELECT 1,3,1
UNION SELECT 2,1,2
UNION SELECT 3,NULL,2
UNION SELECT 4,3,3
UNION SELECT 5,NULL,1
UNION SELECT 6,NULL,NULL
UNION SELECT 7,NULL,2;
SELECT
b.entry_id,
design_status_descrip = d.status_descrip,
stress_status_descrip = s.status_descrip
FROM
@b AS b
LEFT OUTER JOIN @status AS d
ON b.design_status = d.status_id
LEFT OUTER JOIN @status AS s
ON b.stress_status = s.status_id;
答案 3 :(得分:1)
一些方法,首先是效率最高的。
SELECT
e.entry_id
, MAX(CASE WHEN e.design_status = s.status_id THEN s.status_descrip END) AS design_status_descrip
, MAX(CASE WHEN e.stress_status = s.status_id THEN s.status_descrip END) AS stress_status_descrip
FROM
dbo.[Entry] e
LEFT OUTER JOIN
dbo.[Status] s
ON s.status_id = e.design_status
OR s.status_id = e.stress_status
GROUP BY
entry_id
SELECT
e.entry_id
, ds.status_descrip AS design_status_descrip
, ss.status_descrip AS stress_status_descrip
FROM
dbo.[Entry] e
LEFT OUTER JOIN
dbo.[status] ds
ON ds.status_id = e.design_status
LEFT OUTER JOIN
dbo.[status] ss
ON ss.status_id = e.stress_status
答案 4 :(得分:1)
我注意到您的数据中包含NULL
,在这种情况下,使用INNER JOIN
忽略所有答案,因为这将有效地过滤掉任一列中为空的任何行。而是使用左连接。
SELECT
e.entry_id,
ds.status_description,
ss.ststua_description
FROM entry e
LEFT JOIN status ds
ON e.design_status = ds.status_id
LEFT JOIN status ss
ON e.stress_status = ss.status_id