简体   繁体   English

mysql LEFT JOIN与其他表的条件

[英]mysql LEFT JOIN with condition from other table

I have two mysql tables: 我有两个mysql表:

table-1: table_item 表1: table_item

╔════╦═══════╦════════╦══════════╗
║ id ║ catid ║ itemid ║ itemname ║
╠════╬═══════╬════════╬══════════╣
║  1 ║   1   ║   1    ║ Pen      ║
║  2 ║   1   ║   2    ║ Pencil   ║
║  3 ║   1   ║   3    ║ Sharpner ║
║  4 ║   2   ║   4    ║ Book     ║
║  5 ║   2   ║   5    ║ Notebook ║
║  6 ║   3   ║   6    ║ Pant     ║
║  7 ║   4   ║   7    ║ Shirt    ║
╚════╩═══════╩════════╩══════════╝

table-2: bid-2015 表2: 2015年出价

╔════╦════════╦══════╦══════╗
║ id ║ itemid ║ year ║ rate ║
╠════╬════════╬══════╬══════╣
║  1 ║   1    ║ 2015 ║ 3.0  ║
║  2 ║   2    ║ 2015 ║ 5.0  ║
║  3 ║   5    ║ 2015 ║ 7.0  ║
║  4 ║   1    ║ 2016 ║ 3.5  ║
║  5 ║   5    ║ 2016 ║ 7.8  ║
║  6 ║   7    ║ 2016 ║ 20.0 ║
╚════╩════════╩══════╩══════╝

I want to result like below: 我想得到如下结果:

result table: for the year 2015 成绩表:2015年

╔══════════╦══════╦══════╗
║ itemname ║ rate ║ year ║
╠══════════╬══════╬══════╣
║ Pen      ║ 3.0  ║ 2015 ║
║ Pencil   ║ 5.0  ║ 2015 ║
║ Sharpner ║ null ║ null ║
╚══════════╩══════╩══════╝

to get the above result table if I run the below query: 如果我运行以下查询,将获得以上结果表:

SELECT i.itemname, b.rate, b.year
FROM table_item i LEFT JOIN bid-2015 b ON i.itemid=b.itemid
WHERE i.catid=1 AND b.year=2015

then it gives me following output: 然后它给了我以下输出:

╔══════════╦══════╦══════╗
║ itemname ║ rate ║ year ║
╠══════════╬══════╬══════╣
║ Pen      ║ 3.0  ║ 2015 ║
║ Pencil   ║ 5.0  ║ 2015 ║
║ Notebook ║ 7.0  ║ 2015 ║
╚══════════╩══════╩══════╝

How can I LEFT JOIN those tables with conditions so that it can output first table? 我该如何用条件左联接那些表,以便它可以输出第一个表?

A LEFT JOIN is like INNER JOIN except that it will return each record from a at least once, substituting missing fields from b with NULL values, if there are no actual matching records. LEFT JOIN类似于INNER JOIN,不同之处在于它会至少返回一次来自a的每条记录,如果没有实际匹配的记录,则将b中的缺失字段替换为NULL值。

The WHERE condition, however, is evaluated after the LEFT JOIN so the query above checks column after it had been joined. 但是,WHERE条件是在LEFT JOIN之后评估的,因此上面的查询在连接后会检查该列。 No NULL value can satisfy an equality condition, so the records from a without corresponding record from b will unavoidably be filtered out. 没有NULL值不能满足相等条件,因此将不可避免地过滤掉a中的记录而b中没有相应的记录。

Essentially, this query is an INNER JOIN, only less efficient. 本质上,此查询是一个INNER JOIN,仅效率较低。

To match only the records with b.column = 'something' (while still returning all records from a), this condition should be moved into ON clause: 为了只匹配b.column ='something'的记录(同时仍从a返回所有记录),此条件应移至ON子句中:

SELECT i.itemname,b.rate,b.year 
from table_item i 
LEFT JOIN bid-2015 b 
ON i.itemid=b.itemid
AND i.catid=1 AND b.year=2015

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM