我正在将Node.js与mysql模块一起使用,并试图找出如何在两个用户共享类似标签的表中搜索所有实例。我的表的快速演示将是:
username | tag
-------------------
jennifer | coffee
jennifer | pizza
jennifer | travel
joe | sushi
joe | bowling
joe | coffee
joe | travel
celine | singing
celine | pizza
celine | programming
因此,例如,我想找到乔和珍妮弗共有的标签,在这种情况下,这两个标签是两个:咖啡和旅行。搜索他们共有的标签的最佳方法是什么?任何意见将是有益的。提前谢谢!
答案 0 :(得分:1)
这将找到提供2个名称的常用标签:
SELECT tag
FROM yourTable
WHERE username in ("jennifer", "joe")
GROUP BY tag
HAVING count(*) > 1
答案 1 :(得分:0)
应该足够简单:
connection.query('SELECT username, tag from my_table where user="joe" or user="jennifer"', function(err, rows, fields) {
if (err) throw err;
// Reduce results to a list of Joe's tags
const joesTags = rows.filter(function(row) {
return row.username === 'joe';
}).map(function (row) {
return row.tag;
});
// Determine common tags by filtering to tags of Jennifer's that are also in Joe's list
const commonTags = rows.filter(function(row) {
return row.username === 'jennifer' && joesTags.indexOf(row.tag) !== -1
});
});
我确信这不是最有效的方法,但它应该有用。
利用ES6语法(需要Node 4.x或更高版本)的Terser示例:
connection.query('SELECT username, tag from my_table where user="joe" or user="jennifer"', function(err, rows, fields) {
if (err) throw err;
// Reduce results to a list of Joe's tags
const joesTags = rows.filter(row => row.username === 'joe').map(row => row.tag);
// Determine common tags by filtering to tags of Jennifer's that are also in Joe's list
const commonTags = rows.filter(row => row.username === 'jennifer' && joesTags.indexOf(row.tag) !== -1);
});