我有2张桌子,'部门'和'文件'。
表department
| doc_id | dept_name |
----------------------------------
| 1 | Information Technology|
| 2 | Software Development |
| 3 | Human Resource |
| 4 | Accounting |
| 5 | Support |
表document
| doc_id | doc_name | author | description | department |
----------------------------------------------------------------------------
| 1 | Maps | User1 | sample | Information Technology |
| 2 | Audits | User3 | sample | Software Development |
| 3 | Image | User1 | sample | Information Technology |
| 4 | Papers | User4 | sample | Human Resource |
| 5 | Print Screen| User1 | sample | Software Development |
| 6 | Transaction | User3 | sample | Accounting |
| 7 | Graph | User1 | sample | Support |
| 8 | Excel | User1 | sample | Information Technology |
现在,我想显示包含两列的表:department和total_doc。
输出:
| department |total_doc|
-----------------------------------
| Information Technology| 3 |
| Software Development | 2 |
| Human Resource | 1 |
| Accounting | 1 |
| Support | 1 |
我想在部门内显示整个文档,并按升序排列。
这是我的疑问。(不确定)
SELECT department, count(doc_name) as 'total_doc' FROM tbl_document GROUP BY doc_name
我在Codeigniter中使用MVC模式。
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('doc_name');
另外,如何在表格中显示?喜欢在html中使用foreach吗?
答案 0 :(得分:1)
您需要使用department
而不是doc_name
进行分组。
$this->db->select("department, count(doc_name) as 'total_doc'");
$this->db->from('document');
$this->db->group_by('department');
$result = $this->db->get()->result();
希望这会对你有帮助。
foreach ($result as $row)
{
echo $row->department."----".$row->total_doc;
}
答案 1 :(得分:1)
你去吧
SELECT dept_name,COUNT(td.department) FROM department d
LEFT JOIN tdocument td ON td.`department`=d.`dept_name`
GROUP BY td.`department` ORDER BY COUNT(td.`department`) DESC;
答案 2 :(得分:0)
您希望每个部门一行。 IN SQL词:您希望按部门分组。
select department, count(*) as total_doc from document group by department;
(顺便说一句:不要对列别名使用单引号。)