[英]basic sql : selecting AVG() values from the same column multiple times in one query, when each wanted AVG() value uses different WHERE clause
[英]basic sql : selecting the same column multiple times in one query, when each occurrence is dependent on different where clause
執行此查詢的最佳方法是什么。 我有下表
列表的mytable
x y
1 a
2 b
3 c
我想(在偽sql中)
select x as x1 ,x as x2, x as x3 from mytable where ????
什么時候
x1 is x where y=a
x2 is x where y=b
x3 is x where y=c
所以我想結果
1, 2, 3
我目前正在使用cte和一個非常大的數據集,我試圖減少查詢時間,是否總是需要進行3次表掃描?
您應該使用3個查詢。 在自連接時使用適當的索引會更快。 此外,它將更具可讀性。
如果你想要一個查詢調用,它可能是這個:)
SELECT
(SELECT x FROM table WHERE y=1) AS x1,
(SELECT x FROM table WHERE y=2) AS x2,
(SELECT x FROM table WHERE y=3) AS x3
我會這樣做的:
SELECT
tableRowA.x as x1
tableRowB.x as x2
tableRowC.x as x3
FROM
table as tableRowA,
table as tableRowB,
table as tableRowC
WHERE
tableRowA.y = 1
tableRowB.y = 2
tableRowC.y = 3
更容易理解,如果每行需要多列,請提取更多信息
在給出的示例中,只有3行輸入和1行輸出。 我假設至少涉及一個其他列,例如輸入數據:
w x y
---------
w1 1 a
w1 2 b
w1 3 c
w2 4 a
w2 5 b
w2 6 c
.
.
.
是輸出:
w x1 x2 x3
-----------
w1 1 2 3
w2 4 5 6
.
.
.
這可以使用如下查詢一次完成:
select w,
max(case when y = 'a' then x end) x1,
max(case when y = 'b' then x end) x2,
max(case when y = 'c' then x end) x3
from datatable
where y in ('a','b','c')
group by w
另一種方案:
SELECT x, y FROM table WHERE y IN ('a', 'b')
你將得到一個結果集:
x | y
-----
1 | a
2 | b
然后可以在應用程序中使用此結果集來獲得所需結果。
從你的問題看來,你想要一個條件的最后三個實例,或者將三個不同的條件聯系在一起。 以下示例是否滿足您的問題:
mytable:
(unique keys 1..n) (col1)
student-id | course-id | grade
s1 gen101 g1
s1 cmp202 g2
s1 psy303 g3
s1 c4 g4
s2 c1 g5
讓我們說我們只想要有三門特定課程(gen101,cmp202和psy303)的學生,並且忽略其他人的成績。
select gen.student-id as student-id
, gen.grade as gen101-gr
, cmp.grade as cmp202-gr
, psy.grade as psy303-gr
from mytable gen
, mytable cmp
, mytable psy
where gen.course-id = 'gen101'
and gen.student-id = cmp.student-id
and cmp.course-id = 'cmp202'
and cmp.studnet-id = psy.student-id
and psy.course-id = 'psy303'
這應該給出一行:
student-id gen101-gr cmp202-gr psy303-gr
s1 g1 g2 g3
希望能給你足夠的工作。
MySQL 5.5.32架構設置 :
CREATE TABLE Table1
(`x` int, `y` varchar(1))
;
INSERT INTO Table1
(`x`, `y`)
VALUES
(1, 'a'),
(2, 'b'),
(3, 'c')
;
CREATE TABLE mytable
(`x` int, `y` varchar(1))
;
INSERT INTO mytable
(`x`, `y`)
VALUES
(1, 'a'),
(2, 'b'),
(3, 'c')
;
查詢1 :
SELECT x1.x as x1, x2.x as x2, x3.x as x3
FROM mytable x1
INNER JOIN mytable x2 ON x2.y='b'
INNER JOIN mytable x3 ON x3.y='c'
WHERE x1.y='a'
結果 :
| X1 | X2 | X3 |
|----|----|----|
| 1 | 2 | 3 |
SELECT Case When y = 1 Then x1 When y = 2 Then x2 Else x3 End FROM mytable
我的建議是選擇按y列排序或分組的結果,並使用該信息將結果集拆分為多個列表以供應用程序處理。 如果你只想在數據庫中這樣做,恐怕需要多次表掃描(或連接)。
另一個解決方法是將第y列中的信息遷移到另一個表(使用外鍵引用),以便能夠更有效地加入該表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.