我试图使SELECT
查询基于另外两个表数据。 _sites_
数组有5个对象,_cats_
数组现在有12个对象。因此,为了基于这些对象获得news
,我必须重复执行12 * 5
sql查询。 (对于每个类别&站点)MySQL根据两个表选择行
如何减少查询次数?
getSites(function (_sites_) {
getCategories(function (_cats_) {
var array = []
async.each(_sites_, function (site, next) {
async.each(_cats_, function (cat, next2) {
var sql = "SELECT * "+
"FROM news "+
"WHERE category = ? AND site = ? "+
"ORDER BY id DESC LIMIT 30"
db.query(sql, [cat.data, site.data], function (result) {
array = array.concat(temp)
next2()
})
}, function() {
next()
})
}, function() {
// finished
console.log(array)
})
})
})
function getCats (pass) { //get used categories
db.query("SELECT * FROM cat WHERE cat_name in (SELECT news_url.rss_cat FROM news_url)"+
"ORDER by cat_pos ASC", [], function (result) {
var array = []
if(result) {
for (var j = 0; j < result.length; j++) {
array.push({type: 1, data:result[j].cat_name})
};
}
pass(array)
})
}
function getSites (pass) {
db.query("SELECT * FROM news_url", [], function (result) {
var array = []
if(result) {
for (var j = 0; j < result.length; j++) {
array.push({type: 0, data:result[j].rss_site})
};
}
pass(array)
})
}
猫表:(类别)
|id|cat_name|cat_pos|
|1 |Fun | 1 |
|1 |Bomm | 2 |
news_url表:(RSS网站名称和URL)
|id|rss_site|rss_url |rss_cat
|1 |Cnn |http://...|Fun
|2 |Fox |http://...|Bomm
|3 |Cnn |http://...|Bomm
|4 |Routers |http://...|Fun
新闻表:
|id|news_site | news_cat | news_content
|1 | Cnn | Bomm | Some random news content from Cnn
|2 | Cnn | Fun | Some random news content from Cnn
|3 | Fox | Fun | Some random news content from Fox
预期结果是每个类别和网站组合的单独N行限制。如果可以使用一些查询。
有没有一种方法可以在一个查询中加入表格?这听起来可能,但没有看到一些示例数据和预期结果(或至少你的表结构),我不知道。 – AdamMc331
我根据您的建议更新了我的问题,谢谢。 – Lazy
那么,你的意思是每个类别和网站的组合?只是列表中的(cnn,fun),(cnn,bomm),(狐狸,趣味),(狐狸,波恩) – AdamMc331