考试报名
考试报名
考试内容
考试大纲
在线客服
返回顶部

备考刷题,请到

CDA认证小程序

(复合题)数据库中有两个表,users 表中有 3 个字段 (user_id,user_name,create_at),orders 表中有 3 个字段 (order_id,user_id,amount)。 (1)查询 users 表中存在而 orders 表中不存在的 user_id,以下选项中正确的是()。
A. select users.user_id from users left join orders on users.user_id=orders.user_id;
B. select users.user_id from users right join orders on users.user_id=orders.user_id;
C. select users.user_id from users left join orders on users.user_id=orders.user_id where orders.user_id is null;
D. select users.user_id from users right join orders on users.user_id=orders.user_id where users.user_id is null;
上一题
下一题
收藏
点赞
评论
题目解析
题目评论(0)

A 选项以 users 为主表左连接,返回 users 表中所有的 user_id。B 选项以 orders 为主表右连接,返回 orders 表中所有的 user_id。D 选项以 orders 为主表右连接并筛选 users 表中 user_id 为空的记录,返回的是 orders 表中存在而 users 表中不存在的 user_id。而 C 选项以 users 为主表左连接并筛选 orders 表中 user_id 为空的记录,返回的是 users 表中存在而 orders 表中不存在的 user_id。

正确答案是:C。

分析如下:

1. 题目要求查询 `users` 表中存在而 `orders` 表中不存在的 `user_id`,这意味着我们需要找到那些在 `users` 表中有记录但在 `orders` 表中没有对应记录的用户。

2. 选项 A:`select users.user_id from users left join orders on users.user_id=orders.user_id;`
- 这个查询会返回 `users` 表中的所有用户,并且会包括 `orders` 表中匹配的记录(如果有的话)。但是,它不会过滤掉那些在 `orders` 表中没有对应记录的用户。

3. 选项 B:`select users.user_id from users right join orders on users.user_id=orders.user_id;`
- 这个查询会返回 `orders` 表中的所有记录,并且会包括 `users` 表中匹配的记录(如果有的话)。这与题目要求相反,因为我们需要的是 `users` 表中有而 `orders` 表中没有的记录。

4. 选项 C:`select users.user_id from users left join orders on users.user_id=orders.user_id where orders.user_id is null;`
- 这个查询会返回 `users` 表中的所有用户,并且会包括 `orders` 表中匹配的记录(如果有的话)。通过 `where orders.user_id is null` 这个条件,过滤掉了那些在 `orders` 表中有对应记录的用户,只保留 `users` 表中存在而 `orders` 表中不存在的 `user_id`。这正是题目要求的结果。

5. 选项 D:`select users.user_id from users right join orders on users.user_id=orders.user_id where users.user_id is null;`
- 这个查询会返回 `orders` 表中的所有记录,并且会包括 `users` 表中匹配的记录(如果有的话)。通过 `where users.user_id is null` 这个条件,过滤掉了那些在 `users` 表中有对应记录的用户。这个结果与题目要求相反。

因此,选项 C 是正确的。