两个MYSQL表比较唯一行的数量

时间:2015-06-26 21:21:27

标签: php mysql

    Table 1
    ID Customer Tracking
    --------------------
    1  Nick       434
    2  Jhon       437
    3  Nick       456
    4  Mike       544

Table 2
B_ID Customer Process
----------------------
1   Nick      Payment
2   Tom       Payment
3   Nick      Payment
4   Mike      Payment
5   Nick      Payment

    Echo
    Table 1  Table 2
    ------------------
    Nick 2   Nick 3
    Mike 1   Mike 1

如何仅从两个不同的表和计数行中选择simillar值。 如您所见,表1中有2个Nick,表2中有3个Nick。

所以我希望只显示两个表中的类似客户。

2 个答案:

答案 0 :(得分:0)

您可以count每个表格(按名称分组)并加入结果:

SELECT customer1, cnt1, customer2, cnt2
FROM   (SELECT   customer AS customer1, COUNT(*) AS cnt1
        FROM     table1
        GROUP BY customer) t1
JOIN   (SELECT   customer AS customer2, COUNT(*) AS cnt2
        FROM     table2
        GROUP BY customer) t2 ON customer1 = customer2

答案 1 :(得分:0)

编写从每个表中获取客户计数的子查询,然后加入它们。

SELECT t1.customer, t1.count AS Table1, t2.count AS Table2
FROM (SELECT customer, COUNT(*) AS count
      FROM Table1
      GROUP BY customer) AS t1
JOIN (SELECT customer, COUNT(*) AS count
      FROM Table2
      GROUP BY customer) AS t2
ON t1.customer = t2.customer