2013-03-26 96 views
1

我有2個select語句從同一個人的兩張表中提取數據。我知道他們可以通過聯合進行組合,但我無法獲得適合我的語法。mysql結合了多個select語句結果

查詢1:

SELECT SUBSTRING_INDEX(username,'@',1) AS username, 
COUNT(username) as count, 
ROUND(
SUM(
CONVERT(SUBSTRING(contribution_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(focused_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(prepared_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(work_score, -2), UNSIGNED INTEGER) 
)/COUNT(username)/76*100) 
as average 

FROM project_rubrics 
GROUP BY username 
LIMIT 0, 90 

問題2:

SELECT username,COUNT(username) as days FROM logon GROUP BY username 

的公共鏈路用戶名字段。
我想要一個給出每個學生的用戶名,天數和平均值的結果集,但我無法獲得連接或組合選擇來工作。

任何幫助表示讚賞。

+0

的UNION關鍵字是你找什麼見http://www.mysqltutorial.org/sql-union-mysql.aspx – DragonZero 2013-03-26 20:49:34

+0

聯盟將不起作用,除非他改變了第二第二查詢的列名,在這種情況下,會爲每個用戶名創建兩行。 – Robbert 2013-03-26 21:01:10

回答

0

你可以做一個子查詢。

SELECT SUBSTRING_INDEX(username,'@',1) AS username, 
COUNT(username) as count, 
ROUND(
SUM(
CONVERT(SUBSTRING(contribution_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(focused_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(prepared_score, -2), UNSIGNED INTEGER) + 
CONVERT(SUBSTRING(work_score, -2), UNSIGNED INTEGER) 
)/COUNT(username)/76*100) 
as average, 

(SELECT COUNT(username) as days FROM logon WHERE logon.username=project_rubrics.username GROUP BY username) as username_count 

FROM project_rubrics 
GROUP BY username 
LIMIT 0, 90 
+0

不幸的是,這並沒有奏效。它返回的子查詢返回的錯誤超過1行。 – user2213304 2013-03-27 09:58:09

+0

這適用於我(不同的數據庫,但相同的總體思路)。也許你在子查詢中按語句指定表:SELECT COUNT(username)as days FROM logon WHERE logon.username = project_rubrics.username GROUP BY logon.username。 – Robbert 2013-03-27 14:54:46