这有点奇怪,我不知道怎么说标题请跟我一起承担。
所以我有一个这样的表,它存储不同工作的数据:
id | company | contact
----------------------
0 | name1 | Bob
1 | name1 | Mark
2 | name3 | Sam
3 | name1 | Bob
4 | name2 | Nigel
5 | name1 | Bob
6 | name3 | Donald
7 | name1 | Sandy
8 | name3 | Nigel
是否有SQL查询我可以用来查询表格,找出特定公司最常用的联系方式。
所以我想要的理论代码就是:
SELECT "Most Commonly used Contact" FROM table WHERE company = "$company";
是否可以在单个查询中进行,还是多查询作业?
答案 0 :(得分:2)
试试这个SQL查询...
SELECT *, COUNT(*) AS total
FROM table
WHERE company = '$company'
GROUP BY contact
ORDER BY total DESC
LIMIT 1
答案 1 :(得分:1)
基本上,您希望查找按公司分组的联系人数量,然后按实际联系人分组。换句话说:
SELECT COUNT(`id`) as num_contacts, `contact`, `company` FROM `jobtable` GROUP BY `company`, `contact` ORDER BY `company`, num_contacts DESC
或者对于一家公司:
SELECT COUNT(`id`) as num_contacts, `contact` FROM `jobtable` WHERE `company`='$company' GROUP BY `contact` ORDER BY num_contacts DESC