我有以下的sql表结构,我试图使用codeigniter从2个表中获取值。
table: salesman
id sales_name ref_id
1 kevin 174
2 mike 574
3 nick 777
table: sales_report
id salesman_id product purchased_date dispatched
1 2 BF0214 04-November-2011 Yes
2 2 CF0474 09-November-2011 No
3 2 BF0111 10-November-2011 No
4 3 BF0714 15-November-2011 Yes
5 3 BF0435 15-November-2011 Yes
6 2 BF0335 18-November-2011 Yes
7 1 BF0714 22-November-2011 Yes
8 1 BF0335 25-November-2011 Yes
我将salesman_id传递给模型,以便在我的视图中抓取并显示值。
我的html表格如下
Ref ID | Salesman Name | Last product Sold | Sold Date | Dispatched Status
我有怎样查询从salesman表中获取sales_name和ref_id并从sales_report表中获取最新产品名称,dispatched和purchase_date的问题?
例如:
Ref ID | Salesman Name | Last product Sold | Sold Date | Dispatched Status
174 kevin BF0335 25-November-2011 Yes
574 mike BF0335 18-November-2011 Yes
777 nick BF0435 15-November-2011 Yes
答案 0 :(得分:0)
使用
GROUP BY
ORDER BY
完成这项工作
答案 1 :(得分:0)
您需要使用sales_report
,SELECT salesman
中的LEFT JOIN值来获取sales_name
和ref_id
,{{3 } purchased_date
(DESC首先获取最新的第一个而不是最早的第一个),ORDER BY salesman.id
使每个推销员只返回一行。
SELECT * FROM sales_report LEFT JOIN salesman ON sales_report.salesman_id = salesman.id ORDER BY purchased_date DESC GROUP BY salesman.id
答案 2 :(得分:0)
你应该通过两个criteras找到最后一个产品:它的销售日期和它的id;因为有些产品可能会在一天内售出。所以,试试这个 -
SELECT s.ref_id, s.sales_name, sr.product, sr.purchased_date, sr.dispatched FROM salesman s
JOIN (
SELECT salesman_id, product, purchased_date, dispatched FROM (
SELECT salesman_id, product, purchased_date, dispatched, IF(@salesman_id = salesman_id, @i := @i + 1, @i := 1) n, @salesman_id := salesman_id
FROM sales_report, (SELECT @i:= 0, @salesman_id = NULL) vars
ORDER BY salesman_id ASC, purchased_date DESC, id DESC) t
WHERE t.n = 1
) sr
ON s.id = sr.salesman_id;