我有一個關於sql查詢的問題。我真正需要的是選擇所有用戶並選擇他們最喜歡的3個類別。現在,我把它兩個不同的查詢:SQL查詢。如何組合它們
async.waterfall([
cbUsersArray => {
sqlRequest(`
SELECT st.id as studentID, st.firstName as studentFirstName, st.email as studentEmail
FROM dbo.Students st
WHERE st.isActive = 1
AND st.deleted = 0
AND IsNull(st.firstName, '') != ''
AND IsNull(st.email, '') != ''
`, (sqlErr, sqlRes) => {
if(sqlErr){
cbUsersArray(sqlErr)
} else {
cbUsersArray(null, sqlRes)
}
})
},
(usersArray, cbUsersArrayWithFavCats) => {
async.eachLimit(usersArray, asyncEachLimit, (u, cb) => {
sqlRequest(`SELECT TOP 3 bts.BrandCategoryID as catID FROM Students st
JOIN SaleView ss ON (st.ID=ss.userID)
JOIN Sales sa ON (sa.ID=ss.SaleID)
JOIN Brands b ON (b.ID=sa.BrandID)
JOIN KEY_BrandcategoryToSale bts ON (bts.SaleID=sa.ID)
WHERE st.ID = ${u['studentID']}
GROUP BY bts.BrandCategoryID
ORDER BY COUNT(bts.BrandCategoryID) desc`,(sqlErr, sqlRes) => {
if(sqlErr){
} else {
}
cb()
})
},() => {
})
}
],() => {
})
有什麼建議,我怎麼能在一個查詢結合起來,並有類似的結果?
+----+-----------+-----------+-------------+------------------------------+
| ID | StudentID | FirstName | Email | FavoriteCategories |
+----+-----------+-----------+-------------+------------------------------+
| 1 | 123456 | Edward | [email protected] | [{c1ID:1},{c2ID:2},{c3ID:3}] |
+----+-----------+-----------+-------------+------------------------------+
OR
+----+-----------+-----------+-------------+--------+--------+--------+
| ID | StudentID | FirstName | Email | Cat1ID | Cat2ID | Cat3ID |
+----+-----------+-----------+-------------+--------+--------+--------+
| 1 | 123456 | Edward | [email protected] | 1 | 2 | 3 |
+----+-----------+-----------+-------------+--------+--------+--------+
向我們展示的樣品結果從目前的查詢,他們應該如何進行組合。 (以及格式化文本。) – jarlh
你好,這樣的事情。 –
通過將Students表加入到第二個sql語句中,您將得到三行(每個類別一個),您可以爲每個學生解析這三行。 – Sourcery