我正在尝试构建一个比我在数据库方面的经验所做的更复杂的查询。
TABLE:
id - data - type - data3
1 - hello - 1 - 1
2 - goodbye - 1 - 1
3 - goodbye - 1 - 2
4 - goodbye - 2 - 1
5 - hello - 2 - 1
目标是做4件事:
所以返回的最终结果应该是(抱歉令人困惑!):
data, COUNT(data["type"]=1), COUNT(data["type"]=2 AND data["data"] = data)
因此,对于上面的示例表,所需的结果将是:
loop 1 - hello, 2, 1
loop 2 - goodbye, 3, 1
然后,理想情况下,我可以按任何一种方式对结果进行排序。
这是我在尝试发布之前尝试构建的查询,我认为它甚至不接近正确,但它可能有助于说明我想要实现的目标更好:
SELECT
(
SELECT `clicks_network_subid_data`, COUNT(*)
FROM track_clicks
WHERE `clicks_campaign_id`='$id' AND `clicks_click_type` = '1'
) AS keywords,
(
SELECT COUNT(*)
FROM track_clicks
WHERE `clicks_campaign_id`='$id' AND `clicks_click_type` = '2' AND `clicks_network_subid_data` = keywords.clicks_network_subid_data
) AS offer_clicks
GROUP BY keywords.clicks_network_subid_data
ORDER BY keywords.COUNT(*) DESC
我还需要在另一个表上进行JOIN以获取一个或多个数据,但是我想我可以在得到这个部分后处理它。
答案 0 :(得分:1)
您可以使用IF-function进行此操作
SELECT `clicks_network_subid_data`,
SUM(IF(clicks_click_type` == '1',1,0)) as keywords,
SUM(IF(clicks_click_type` == '2',1,0)) as offer_clicks,
FROM track_clicks
GROUP BY clicks_network_subid_data
ORDER BY clicks_network_subid_data DESC
答案 1 :(得分:0)
您可以使用GROUP BY执行此操作:
SELECT data, COUNT(*) AS cnt FROM `table` GROUP BY type ORDER BY COUNT(*)
订购可能会变得有点慢,因为这是一个计算字段,但如果你没有大的结果集那么你就可以了。
答案 2 :(得分:0)
首先你的问题有点不清楚,但是,请检查此查询。我怀疑你需要在列(单个)而不是行中计算结果。
select * , count(type_one) as t1_count , count(type_two) as t2_count from (
select data,if(tmp.type=1,1,0) as type_one, if(tmp.type=2,1,0) as type_two from (
select 1 as id , 'hello' as data , 1 as type , 1 as data3 union
select 2 as id , 'goodbye' as data , 1 as type , 1 as data3 union
select 3 as id , 'goodbye' as data , 1 as type , 2 as data3 union
select 4 as id , 'goodbye' as data , 2 as type , 1 as data3 union
select 5 as id , 'hello' as data , 2 as type , 1 as data3
) tmp
) tmp2
group by tmp2.type_one ;
让我知道这是否适合您
欢呼:)