mysql查询不返回预期的结果

时间:2015-11-12 05:59:17

标签: mysql join

我有两个mysql表。

table-1:table-item:

id  | itemid | itemname | catid
---------------------------------
1   |   1    |  Pen     |  1
2   |   2    |  Pencil  |  1
3   |   3    | Sharpner |  1
4   |   4    |  Book    |  2
5   |   5    |  Khata   |  2
6   |   6    |  Bag     |  3 
7   |   7    |  File    |  3  
---------------------------------

table-2:annual-item:

id  | itemid |catid| year
-----------------------------
1   |   1    |  1  | 2015
2   |   3    |  1  | 2015
3   |   4    |  2  | 2015
4   |   6    |  3  | 2015
5   |   1    |  2  | 2016
6   |   1    |  1  | 2016  
------------------------------

我想从2016年catid-1获取table-item的{​​{1}}项目列表,这些项目在yearly-item表格中不存在。

id  | itemid | itemname | catid
---------------------------------
2   |   2    |  Pencil  |  1
3   |   3    | Sharpner |  1
---------------------------------

为此目的,在执行此查询时:

SELECT * FROM table_item t LEFT JOIN yearly_item y ON t.itemid=y.itemid AND t.catid=y.catid WHERE t.catid=1 AND y.year='2016' AND y.itemid IS NULL

它给出了这个结果:

MySQL returned an empty result set (i.e. zero rows).

1 个答案:

答案 0 :(得分:0)

尝试

select b.itemid, b.itemname, b.catid, a.year 
from yearly_item a, item b
where year = 2016
and b.itemid != a.itemid
and b.catid = 1
and a.catid = 1

http://sqlfiddle.com/#!9/cfd66/14/0