Home > Database > Mysql Tutorial > body text

mysql左连接自连接例子

WBOY
Release: 2016-06-07 15:19:24
Original
1186 people have browsed it

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入 连接就是将两个表按照某个公共字段来拼成一个大表。 左连接就是在做连接是以左边这个表为标准,来遍历右边的表。 1、引子 左连接,自连接 [sql] view plaincopySELECT * FROM test_visit t1 LEFT JOI

欢迎进入Linux社区论坛,与200万技术人员互动交流 >>进入

  连接就是将两个表按照某个公共字段来拼成一个大表。

  左连接就是在做连接是以左边这个表为标准,来遍历右边的表。

  1、引子

  左连接,自连接

mysql左连接自连接例子

  [sql] view plaincopySELECT * FROM test_visit t1 LEFT JOIN test_visit t2 ON t1.uid = t2.uid

  结果:

mysql左连接自连接例子

  2、问题 例子:

  用户访问记录:

mysql左连接自连接例子

  问题:查出看了湖南卫视但没有看北京卫视的用户信息

  逻辑:先通过左连接将看了湖南卫视和北京卫视的查出来,然后再将看了湖南卫视但不在刚才查出的结果中的用户查出来。

  [sql] view plaincopy

  SELECT * FROM test_visit WHERE channel='湖南卫视' AND uid NOT IN (

  SELECT DISTINCT t1.uid FROM test_visit t1 LEFT JOIN test_visit t2 ON t1.uid = t2.uid

  WHERE t1.channel='湖南卫视' AND t2.channel='北京卫视' )

  结果:

mysql左连接自连接例子

  各位大神,有什么好的方法,说说吧,我感觉这个不是最优的

mysql左连接自连接例子

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!