mysql - Simple select query in single table
问题描述
I have table orders, it has many columns, but I am interested in these, user_id and article_id.
|--------------------|-----------------|------------|
| user_id | article_id | Name |
|--------------------|-----------------|------------|
| 1 | 115 | John |
| 1 | 55 | John |
| 2 | 115 | Mike |
| 2 | 49 | Mike |
| 3 | 115 | Dave |
| 3 | 55 | Dave |
|--------------------|-----------------|------------|
I need to make a query that selects those users that have article_id 115 and 55. Desired result in this example is to get users named John and Dave, since both of them have 115 and 55. There is no column Name, I just added it to for better understanding.
I have tried this query:
SELECT * FROM orders AS o
WHERE o.article_id IN (55, 115)
ORDER BY o.user_id
But I get all article_id and user_id. I know I should use another select to select only those users with 55 and 115... but I am stuck.
解决方案
Use group by
and having
. Assuming you don't have duplicates in the table:
SELECT o.user_id, o.name
FROM orders o
WHERE o.article_id IN (55, 115)
GROUP BY o.user_id, o.name
HAVING COUNT(*) = 2; -- has both
推荐阅读
- performance - 为什么 arm64 ABI 中不使用 SVC 的立即数?
- javascript - 两个 Django 表单 - 带有两个提交按钮的 Html 页面
- python - Tensorflow keras model.save 使用自定义层引发 InaccessibleTensorError
- docker - 从 docker 容器提交时,Spark 作业未安排给工作人员
- csvhelper - 使用 CsvHelper 将不同的列标题名称映射到 C# 实体类中的单个字段
- reactjs - react dropzone,限制上传的图片数量,超过限制时给出错误消息
- amazon-web-services - 如何监控和调试 AWS 中对 s3 的每个请求?
- actions-on-google - 已部署但未调用 Google 操作
- java - 通过 LAN 建立 Java 网络
- react-native - 如何将json字符串从react-native中的fetch转换为对象