博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
SQL题目
阅读量:5836 次
发布时间:2019-06-18

本文共 1329 字,大约阅读时间需要 4 分钟。

hot3.png

 有如下数据表

create table test (NAME varchar(20) not null, HOBBY varchar(20) not null);   insert into test values('Adam','basketball'); insert into test values('Bill','basketball'); insert into test values('Bill','football'); insert into test values('Cyper','basketball'); insert into test values('Cyper','badminton'); insert into test values('David','basketball'); insert into test values('David','badminton'); insert into test values('David','table tennis');
 

使用SQL语句查出hobby即包含basketball,又包含badminton的name所在的行:

即第5, 6 ,7 ,8行

 

 

我想了几种SQL语句。不知道还没有有别的。

--(1)withWITH  NAME_MATCHES AS     (SELECT NAME        FROM TEST        WHERE HOBBY IN ('basketball', 'badminton')        GROUP BY NAME        HAVING COUNT(NAME) = 2)SELECT T.*  FROM TEST AS T, NAME_MATCHES AS NM  WHERE T.NAME = NM.NAME;--(2)exists and existsSELECT *  FROM TEST AS T1  WHERE EXISTS (SELECT *          FROM TEST AS T2          WHERE T2.NAME = T1.NAME AND HOBBY = 'basketball')    AND EXISTS (SELECT *          FROM TEST AS T3          WHERE T3.NAME = T1.NAME AND HOBBY = 'badminton');--(3)self joinSELECT T1.*  FROM TEST AS T1, TEST AS T2, TEST AS T3  WHERE T1.NAME = T2.NAME AND T1.NAME = T3.NAME AND T2.HOBBY = 'basketball'    AND T3.HOBBY = 'badminton';
 

第1种是我目前采纳的,稍微有点长

第3种最简单,可是扩展性不好,当hobby增多时,参数不好处理。

 

欢迎讨论(各种数据库都可以)

 

 

 

 

 

 

转载于:https://my.oschina.net/uniquejava/blog/225025

你可能感兴趣的文章
Python version 2.7 required, which was not found in the registry
查看>>
Android API level 与version对应关系
查看>>
Team Name
查看>>
String类
查看>>
西门子_TDC_数据耦合小经验
查看>>
接口测试与postman
查看>>
mac zsh选择到行首的快捷键
查看>>
LINQ To XML的一些方法
查看>>
[LeetCode] Copy List with Random Pointer
查看>>
openstack部署之nova
查看>>
JS组件系列——表格组件神器:bootstrap table
查看>>
存储过程Oracle(一)
查看>>
log4j日志归档
查看>>
Java笔记01——IO流
查看>>
mysql遇见error,1049
查看>>
NYOJ311 完全背包
查看>>
codevs——2822 爱在心中
查看>>
Python基础班---第一部分(基础)---Python基础知识---认识Python
查看>>
JAVA MAC 配置
查看>>
1134 最长上升子序列 (序列型 DP)
查看>>