我有一张这样的表:
// friends
+----+---------+--------+
| id | user_id | friend |
+----+---------+--------+
| 1 | 1 | Peter |
| 2 | 1 | Martin |
| 3 | 2 | Jack |
| 4 | 1 | Barman |
| 5 | 3 | Peter |
| 6 | 1 | Jack |
| 7 | 3 | David |
| 8 | 2 | David |
| 9 | 3 | Martin |
+----+---------+--------+
现在我有两个user_ids。例如1
和3
。现在我想匹配有共同朋友的行。所以这是预期的结果:
| Peter |
| Martin |
因为Peter
和Martin
对于1
和3
都很常见。
纯sql可以做到这一点吗?
答案 0 :(得分:1)
您可以对user_id
表进行自联接,并且需要以下三个条件来匹配联接两侧的记录:
3
为SELECT t1.friend
FROM friends t1
INNER JOIN friends t2
ON t1.user_id = 1 AND
t2.user_id = 3 AND
t1.friend = t2.friend
import sys
reload(sys)
sys.setdefaultencoding("utf-8")
为 var current_page_size = $(this).width();
if (current_page_size >= 800) {
$('#calendar').fullCalendar({
yearColumns: 3,
});
} else {
yearColumns: 1,
}
try {
InputStream is = new FileInputStream(excelFileName);
Workbook wb = WorkbookFactory.create(is);
Sheet sheet = wb.getSheet(sheetName);
Row row = sheet.getRow(2);
Cell cell = row.getCell(3);
if (cell == null) {
cell = row.createCell(3);
}
is.close();
cell.setCellType(Cell.CELL_TYPE_STRING);
System.out.println(cell.getStringCellValue());
FileOutputStream os = new FileOutputStream(excelFileName);
cell.setCellValue("test");
wb.write(os);
os.close();
wb.close();
} catch (IOException | InvalidFormatException e) {
e.printStackTrace();
}
如果您正确设置了索引,我希望这比聚合方法运行得更快。
在这里演示:
答案 1 :(得分:1)
试试这个:
SELECT friend
FROM friends
WHERE user_id IN (1, 3)
GROUP BY friend HAVING COUNT(DISTINCT friend) = 2;
答案 2 :(得分:0)
另一种方式
SELECT friend
FROM t
GROUP BY friend
HAVING SUM(user_id =1)>0
AND SUM(user_id =3)>0