簡體   English   中英

需要使用subselect獲得一行結果

[英]Need to get one row of result with subselect

有這樣的SQL查詢:

SELECT 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 1") AS test_1 , 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 2") AS test_2 , 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 3") AS test_3 
FROM `table_name` GROUP BY `content`

並得到這樣的結果:

test_1, test_2, test_3
2,      7,      0
2,      7,      0
2,      7,      0
2,      7,      0
2,      7,      0
2,      7,      0
2,      7,      0
2,      7,      0
2,      7,      0
2,      7,      0

只需要一行就可以得到結果,像這樣:

test_1, test_2, test_3
2,      7,      0

怎么樣? 我的查詢出了什么問題?

檢查一下。

SELECT  distinct 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 1") AS test_1 , 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 2") AS test_2 , 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 3") AS test_3 
FROM `table_name` GROUP BY `content`

您的查詢應該這樣重寫:

SELECT 
    SUM(CASE WHEN `content` = "test 1" THEN 1 ELSE 0 END) AS test_1,
    SUM(CASE WHEN `content` = "test 2" THEN 1 ELSE 0 END) AS test_2,
    SUM(CASE WHEN `content` = "test 3" THEN 1 ELSE 0 END) AS test_3
FROM 
    `table_name`
WHERE 
    `custom_id` IN (10,9,8,6,5,4,3,2,1);

只需在您的SELECT語句中添加TOP子句即可。

SELECT TOP 1
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 1") AS test_1 , 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 2") AS test_2 , 
(SELECT COUNT(`id`) FROM `table_name` WHERE `custom_id` IN (10,9,8,6,5,4,3,2,1) AND `content` = "test 3") AS test_3 
FROM `table_name` GROUP BY `content`

你在做什么沒有多大意義。 您從表中選擇並按內容分組。 這意味着您為每個內容獲得一個結果行(一個用於“ test 1”,一個用於“ test 2”,等等)。 表中顯示了十個不同的內容,因為您顯示將獲得十個結果行。

然后,對於每一個這樣的行,無論它包含什么內容,您都在執行三個子查詢,這些子查詢當然總是得到相同的結果。

所以:

select 
  (select count(*) from table_name 
    where custom_id in (10,9,8,6,5,4,3,2,1) and content = 'test 1') as test_1 , 
  (select count(*) from table_name 
    where custom_id in (10,9,8,6,5,4,3,2,1) and content = 'test 2') as test_2 , 
  (select count(*) from table_name
    where custom_id in (10,9,8,6,5,4,3,2,1) and content = 'test 3') as test_3 ;

或更好:

select 
  sum(content = 'test 1') as test_1,
  sum(content = 'test 2') as test_2,
  sum(content = 'test 3') as test_3
from table_name
where custom_id in (10,9,8,6,5,4,3,2,1);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM