有这样的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
如何?我的查询有什么问题?
答案 0 :(得分:1)
检查这个。
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`
答案 1 :(得分:0)
您的查询应该像这样重写:
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);
答案 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`
答案 3 :(得分:-1)
你在做什么并没有多大意义。您可以从表中选择并按内容分组。这意味着每个内容得到一个结果行(一个用于'测试1',一个用于'测试2'等)。您的表中似乎有十个不同的内容,因为您显示您有十个结果行。
然后对于每一个这样的行,无论它包含什么,你都在执行你的三个子查询,当然总是会得到相同的结果。
所以:
Datasource(ds => ds.Json(Model).UpdateURL("Templates/Update").InsertURL("Templates/Insert").RemoveURL("Templates/Delete").Adaptor(AdaptorType.RemoteSaveAdaptor))
或更好:
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 ;