示例场景:
三个表:员工,雇主,垂直市场
员工(员工):
| id | fname | lname | employerid|
-----------------------------------
| 108 | John | Doe | 12 |
| 221 | Jane | Doe | 12 |
| 286 | Rob | Smith | 43 |
雇主(雇主):
| id | name | vmarketid|
----------------------------
| 12 | Lowes | 1 |
| 15 | Target | 1 |
| 43 | Chase | 2 |
垂直市场(vmarket):
| id | name |
--------------------
| 1 | retail |
| 2 | banking |
| 3 | healthcare |
我正在处理一组查询,以便与基于Web的报告前端一起使用。第一个查询将填充垂直市场的下拉列表,并添加一个全部'位置0处的选项:
select 0, 'All'
union
select `id`, `name` from vmarket
第二个菜单通过存储过程填充,该存储过程根据第一个菜单中的选择选择市场类型的所有可能雇主(同时在第0个位置添加'全部')
CREATE DEFINER=`reports`@`%` PROCEDURE `sp_MarketEmployerSearch`(
market_id INT
)
BEGIN
SELECT 0, 'All'
UNION
SELECT `id`, `name`
FROM employer
WHERE `vmarketid` = market_id;
END$$
第三个问题是我的问题和目标的来源。我有另一个程序,我想根据两个选项返回员工信息,无论是All / All还是Retail / Lowes。显然,根据两个明确定义的值进行选择很容易,但是如果用户选择All / All,我可以使用query / conditions来允许所有行返回?
如果有人从菜单中选择零售/低价,这是返回结果的明显语法:
CREATE DEFINER=`reports`@`%` PROCEDURE `sp_EmployeeInfo`(
market_id INT
employer_id INT
)
BEGIN
SELECT employee.`lname` AS `Employee Last Name`,
employee.`fname` AS `Employee First Name`,
employer.`name` AS `Employer Name`,
vmarket.`name` AS `Market Name`
FROM employee
LEFT JOIN employer ON employee.`employerid` = employer.`id`
LEFT JOIN vmarket ON employer.`vmarketid` = vmarket.`id`
WHERE vmarket.`id` = market_id AND employer.`id` = employer_id
ORDER BY vmarket.`name`,employer.`name`,employee.`lname`;
END$$
动态回归' All'唯一可以想到的事情。整个垂直市场甚至所有市场/所有雇主的记录都是WHERE子句中的某种情况,但我知道这不是解决方案。如果这不是答案,那么我有什么选择可以退回,比如说,所有在零售业工作的员工,无论商店如何(根据第一个菜单,vmarketid为1,employeeid为0,根据第二个菜单返回所有雇主。
感谢任何帮助!
答案 0 :(得分:0)
如果我了解你的目标是什么,这个解决方案对我有用:
SELECT employee.lname AS [Employee Last Name],
employee.fname AS [Employee First Name],
employer.name AS [Employer Name],
vmarket.name AS [Market Name]
FROM employee
LEFT JOIN employer ON employee.employerid = employer.id
LEFT JOIN vmarket ON employer.vmarketid = vmarket.id
WHERE (vmarket.id = market_id OR market_id=0) AND (employer.id = employer_id OR employer_id=0)
ORDER BY vmarket.name,employer.name,employee.lname;