mysql 三表连查LEFT JOIN
时间: 2023-10-12 16:05:14 浏览: 104
在MySQL中,LEFT JOIN用于连接两个表并获取左表的全部记录,即使右表没有对应的匹配记录。基本语法如下:
```
SELECT * FROM table1 LEFT JOIN table2 ON condition
```
在这个语句中,table1是左表,table2是右表,condition是连接条件。LEFT JOIN会返回左表和右表的所有匹配记录,如果右表没有匹配的记录,则会返回NULL值。
关于三表连查的LEFT JOIN,可以使用相同的语法结构来连接三个表。例如,如果要连接items、item_visit_stats和item_trade_stats这三个表,可以这样写:
```
SELECT * FROM items
LEFT JOIN item_visit_stats ON items.num_iid = item_visit_stats.num_iid
LEFT JOIN (SELECT num_iid, SUM(buyer_num) AS buyer_num, SUM(item_num) AS item_num FROM item_trade_stats) AS trade_stats
ON items.num_iid = trade_stats.num_iid
```
这个查询语句将会返回items表的所有记录,并根据num_iid字段连接item_visit_stats和item_trade_stats表。注意,在连接item_trade_stats表时,使用了子查询来计算SUM(buyer_num)和SUM(item_num)。
这样的LEFT JOIN语句可以帮助我们获取三个表的关联数据,并且即使右表没有匹配的记录,左表的记录也会被包含在结果中。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *3* [MySql的join(连接)查询 (三表 left join 写法)](https://blog.csdn.net/weixin_42202605/article/details/113254432)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
- *2* [MySQL表LEFT JOIN左连接与RIGHT JOIN右连接的实例教程](https://download.csdn.net/download/weixin_38653687/13695747)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 50%"]
[ .reference_list ]
阅读全文