mysql - 使用 MYSQL 查询加入 2 个带有 if 条件的表
问题描述
我有 2 个表:用户和 prov_spec_search。我正在寻找一个 sql 查询来加入具有以下条件的这些表:
users Table:
id | first_name | last_name | activ_status
-------------------------------------------
6 | sudha | dravid | 1
7 | Gokul | menon | 1
13 | sujith | nair | 1
-------------------------------------------
prov_spec_search 表
id | inv_user_id | drafter_id | proj_status
-------------------------------------------
1 | 13 | 7 | Ongoing
2 | 13 | 6 |
-------------------------------------------
预期结果是:
Need to join users and prov_spec_search tables with 2 conditions where
users.id = prov_spec_search.drafter_id
AND
if project_status = Ongoing then the result proj_status should show 'Not Available'.
if proj_status is null then should show 'Availabe'.
if no drafters_id or no records found then from users table it should show the users name with option(proj_status) 'Available'
结果:
Name | proj_status
------------------------------
Gokul Menon | Not Available
sudha dravid | Available
sujith Nair | Available
我从这个查询开始:
SELECT
CONCAT(users.first_name, ' ', users.last_name) AS drafter_name,
users.id AS id,
users.activ_status,
prov_spec_search.proj_current_status
FROM users
LEFT JOIN prov_spec_search ON users.id = prov_spec_search.drafter_id
WHERE (users.activ_status ='1')
解决方案
与CASE
:
SELECT
CONCAT(users.first_name, ' ', users.last_name) AS drafter_name,
CASE prov_spec_search.proj_status
WHEN 'Ongoing' THEN 'Not Available'
ELSE 'Available'
END proj_status
FROM users LEFT JOIN prov_spec_search
ON users.id = prov_spec_search.drafter_id
WHERE (users.activ_status ='1')
请参阅演示。
结果:
| drafter_name | proj_status |
| ------------ | ------------- |
| Gokul menon | Not Available |
| sudha dravid | Available |
| sujith nair | Available |
推荐阅读
- dax - LOOKUPVALUE 基于 DAX 中的聚合函数
- here-api - here-api - 计算路线距离
- tcl - 在“array”集合中创建新命令时出现问题
- python - 加快循环时间迭代 Python 中相对较大的 Excel 工作表
- excel - 从 Excel 中的范围创建唯一值列表
- ruby - 在 routes.rb 中添加页面链接/锚点到 Rails 资源
- apache-spark - 将火花特征转换管道导出到文件
- javascript - 在这种情况下,什么是“生成”?
- python - 如果在以前的版本中训练,张量流模型会给出不同的结果吗
- sql-server - 带有两个 raiserrors 的存储过程