如何在Mysql Select Query中计算和获取两行的结果?

时间:2014-12-14 06:01:50

标签: mysql sql join count select-query

这是我的表结构。 有时table1数据我的重复(例如:实际上Id 1应该只有4行但有时由于重复而为8)所以避免重复我在select查询中使用 GROUP BY 命令

表1

|id| website|time|
-----------------
|01|facebook|20.0|
|01|google  |40.0|
|01|youtube |10.0|
|01|ebay    |30.0|
|02|facebook|50.0|
|02|ebay    |50.0|

表2

    |id|marks|
    ----------- 
    |01|   80|
    |02|   90|
    |03|   70|
    |04|  100|

我想选择具体的(标记)(Facebook上的时间)(google& youtube上的时间计数)用户

以下选择查询为用户ID'01'提供(标记)(Facebook上的时间)

如何在同一查询中接收id'1'的google和youtube的时间计数?

SELECT table2.id,table2.marks, table1.time
FROM table1
RIGHT JOIN table2 ON table1.id= table2.id
WHERE table1.website LIKE ('%facebook%')
AND table1.id=  '01'
GROUP BY table1.id, table1.website

3 个答案:

答案 0 :(得分:1)

您希望在facebook上找到时间,然后为特定用户找到youtubegoogle的总和,您可以使用mysql conditional sum来实现它

select
sum(case when t1.website = 'facebook' then t1.time else 0 end) as `fb_time`,
(
  sum(case when t1.website='google' then t1.time else 0 end)+
  sum(case when t1.website='youtube' then t1.time else 0 end)
)
as `google_youtube`,
t2.marks
from table1 t1
join table2 t2 on t1.id = t2.id
where t1.id = '01' 

如果您需要为所有用户计算相同的内容,那么您可以将其作为

进行计算
select
t1.id,
sum(case when t1.website = 'facebook' then t1.time else 0 end) as `fb_time`,
(
  sum(case when t1.website='google' then t1.time else 0 end)+
  sum(case when t1.website='youtube' then t1.time else 0 end)
)
as `google_youtube`,
t2.marks
from table1 t1
join table2 t2 on t1.id = t2.id
group by t1.id

答案 1 :(得分:0)

如果我正确理解您的查询,我认为您需要使用子查询。 以下子查询返回两个计数; time_on_facebook& time_on_google_and_youtube 适用于所有用户

SELECT t1.id, t2.marks, 
COUNT(t1.time) as time_on_facebook, 
(SELECT COUNT(t1_sq.time)
FROM `table1` as t1_sq
WHERE (t1_sq.website = "youtube" OR t1_sq.website = "google") 
AND t1_sq.id = t1.id
GROUP BY t1.id)  as time_on_google_and_youtube 
FROM `table1` as t1
LEFT JOIN table2 t2 ON t2.id = t1.id
WHERE t1.website = "facebook"
GROUP BY t1.id

要将其限制为用户id = 01,请添加WHERE子句

SELECT t1.id, t2.marks, 
COUNT(t1.time) as time_on_facebook, 
(SELECT COUNT(t1_sq.time)
FROM `table1` as t1_sq
WHERE (t1_sq.website = "youtube" OR t1_sq.website = "google") 
AND t1_sq.id = t1.id
GROUP BY t1.id)  as time_on_google_and_youtube 
FROM `table1` as t1
LEFT JOIN table2 t2 ON t2.id = t1.id
WHERE t1.website = "facebook" AND t1.id = 1
GROUP BY t1.id

您确定要COUNT(时间)还是想要SUM(时间)? 最后,考虑为两个表添加主键,并且为了清楚起见,可以将“id”列重命名为“user_id”。

答案 2 :(得分:0)

不清楚你想要的输出是什么样的。我提出了一个问题, 但没试过。尝试一下,让我知道它是否有效。

select t1.id, t1.website, sum(t1.time) as total_time, max(t2.marks) as marks 
from table1 as t1
left join table2 as t2
on t1.id = t2.id
where t1.website = 'facebook'
and t1.id = '01'
group by t1.id, t1.website

UNION

select t1.id, t1.website, sum(t1.time) as total_time, max(t2.marks) as marks 
from table1 as t1
left join table2 as t2
on t1.id = t2.id
where t1.website IN ('youtube', 'google')
and t1.id= '01'
group by t1.id, t1.website