我有两张表正在关注
表名:stockIn
+----+-------------+------------+------------+
| Id | date | Itemname | stockInqty |
+====+=============+============+============+
| 1 | 12/12/2014 | testitem | 12 |
| 2 | 14/12/2014 | testitem11 | 20 |
+----+-------------+------------+------------+
表名:stockOut
+----+------------+-------------+-------------+
| Id | date | Itemname | stockOutqty |
+====+============+=============+=============+
| 1 | 12/12/2014 | testitem | 7 |
| 2 | 13/12/2014 | testitem11 | 15 |
+----+------------+-------------+-------------+
我需要在两个日期之间按照
的顺序组合testitem记录+------------+-----------+-------------+-------------+
| date | itemname | stockInqty | stockOutqty |
+============+===========+=============+=============+
| 12/12/2014 | testitem | 12 | 7 |
| 13/12/2014 | testitem | NIL | 15 |
| 14/12/2014 | testitem | 20 | NIL |
+------------+-----------+-------------+-------------+
我收到了这样的查询
SELECT t1.`date`
, t1.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 LEFT JOIN tbl2 t2 ON t1.`date` = t2.`date`
AND t1.itemname = t2.itemname
UNION
SELECT t2.`date`
, t2.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 RIGHT JOIN tbl2 t2 ON t1.`date` = t2.`date`
AND t1.itemname = t2.itemname
查询结果将如下
+-------------+------------+------------+-------------+
|date | itemname | stockInqty | stockOutqty |
+=============+============+============+=============+
| 12/12/2014 | testitem | 12 | 7 |
| 14/12/2014 | testitem | 20 | NIL |
| 13/12/2014 | testitem | NIL | 15 |
+-------------+------------+------------+-------------+
结果是根据第一张表数据排序的。
我需要根据日期对结果进行排序(即,第一条记录必须在12/12/2014
上,第二条记录在13/14/2014
上的14/12/2014
三分之一。)
提前致谢。
答案 0 :(得分:0)
按日期排序
尝试此操作SELECT t1.`date`
, t1.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 LEFT JOIN tbl2 t2 ON t1.`date` = t2.`date`
AND t1.itemname = t2.itemname
UNION
SELECT t2.`date`
, t2.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 RIGHT JOIN tbl2 t2 ON t1.`date` = t2.`date`
AND t1.itemname = t2.itemname order by date
答案 1 :(得分:0)
使用此代码:
select date,itemname,stockInqty,stockOutqty from(
SELECT t1.date
, t1.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 LEFT JOIN tbl2 t2 ON t1.date = t2.date
AND t1.itemname = t2.itemname
UNION
SELECT t2.date
, t2.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 RIGHT JOIN tbl2 t2 ON t1.date = t2.date
AND t1.itemname = t2.itemname)
order by date
答案 2 :(得分:0)
select * from
(
SELECT t1.date as sdate
, t1.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 LEFT JOIN tbl2 t2 ON t1.`date` = t2.`date`
AND t1.itemname = t2.itemname
UNION
SELECT t2.date as sdate
, t2.itemname
, t1.stockInqty AS stockInqty
, t2.stockInqty AS stockOutqty
FROM tbl1 t1 RIGHT JOIN tbl2 t2 ON t1.`date` = t2.`date`
AND t1.itemname = t2.itemname
) t
order by sdate