我有4个子查询需要作为一个单元运行,并在1个列表中检索不同的结果。我的java应用程序将使用Spring Data JPA存储库调用此查询,它应该返回一个List。
## S_NAME based on TABLE_1.Id = 1
SELECT DISTINCT(S_NAME) FROM TABLE_1 WHERE S_ID = 1;
## I_NAME based on TABLE_1.Id = 1
SELECT DISTINCT(I_NAME) FROM I_TABLE WHERE I_ID
IN (SELECT I_ID FROM E_TABLE WHERE S_ID = 1);
## C_NAME based on TABLE_1.Id = 1
SELECT DISTINCT(C_NAME) FROM C_TABLE WHERE C_ID
IN (SELECT C_ID FROM C_TABLE WHERE E_ID
IN (SELECT E_ID FROM E_TABLE WHERE S_ID = 1));
## P_NAME based on TABLE_1.Id = 1
SELECT DISTINCT(P_NAME) FROM P_TABLE WHERE C_ID
IN (SELECT C_ID FROM C_TABLE WHERE E_ID
IN (SELECT E_ID FROM E_TABLE WHERE S_ID = 1));
S_NAME,I_NAME,C_NAME和P_NAME列包含相同的数据。只是不同的名称,所以我们知道该数据的来源。但是,对于此查询,我需要来自1列中所有这些列的不同结果。
这可以在不进行存储过程的情况下轻松完成吗?我愿意,但我没有这种东西的授权。制作视图时的相同构造。
答案 0 :(得分:0)
您可以使用union all
获取行中的值或将它们放在不同的列中。这是一种方式:
SELECT (SELECT DISTINCT(S_NAME) FROM TABLE_1 WHERE S_ID = 1
) as val1,
(SELECT DISTINCT(I_NAME) FROM I_TABLE WHERE I_ID IN (SELECT I_ID FROM E_TABLE WHERE S_ID = 1
) as val2,
(SELECT DISTINCT(C_NAME) FROM C_TABLE
WHERE C_ID IN (SELECT C_ID FROM C_TABLE WHERE E_ID IN (SELECT E_ID FROM E_TABLE WHERE S_ID = 1))
) as val3,
(SELECT DISTINCT(P_NAME) FROM P_TABLE
WHERE C_ID IN (SELECT C_ID FROM C_TABLE WHERE E_ID IN (SELECT E_ID FROM E_TABLE WHERE S_ID = 1))
) as val4;
虽然查询类似,但我不确定是否值得尝试将它们合并。
答案 1 :(得分:0)
使用UNION
,这意味着render partial: @article, locals: { full: true }
,因此您无需这样说:
render @article, full: true
仅供参考:第三个查询是双读DISTINCT
,这是一种浪费。我把它放在一边,假设设置这个例子是一个简单的错误。
答案 2 :(得分:0)
SELECT (S_NAME) FROM TABLE_1 WHERE S_ID = 1;
UNION
SELECT (I_NAME) FROM I_TABLE WHERE I_ID
IN (SELECT I_ID FROM E_TABLE WHERE S_ID = 1);
UNION
SELECT (C_NAME) FROM C_TABLE WHERE C_ID
IN (SELECT C_ID FROM C_TABLE WHERE E_ID
IN (SELECT E_ID FROM E_TABLE WHERE S_ID = 1));
-- HERE UNION will only Take DISTINCT row from the each query no need of Distinct
UNION
SELECT (P_NAME) FROM P_TABLE WHERE C_ID
IN (SELECT C_ID FROM C_TABLE WHERE E_ID
IN (SELECT E_ID FROM E_TABLE WHERE S_ID = 1));