如何匹配常见行?

时间:2017-04-03 08:54:27

标签: mysql sql select group-by having

我有一张这样的表:

// 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。例如13。现在我想匹配有共同朋友的行。所以这是预期的结果:

| Peter  |
| Martin |

因为PeterMartin对于13都很常见。

纯sql可以做到这一点吗?

3 个答案:

答案 0 :(得分:1)

您可以对user_id表进行自联接,并且需要以下三个条件来匹配联接两侧的记录:

  1. 第一个表格中的3SELECT t1.friend FROM friends t1 INNER JOIN friends t2 ON t1.user_id = 1 AND t2.user_id = 3 AND t1.friend = t2.friend
  2. 第二个表格中的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, }
  3. 朋友匹配(即由双方共享)

  4.  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();
        }
    

    如果您正确设置了索引,我希望这比聚合方法运行得更快。

    在这里演示:

    Rextester

答案 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