MySQL:根据另一个表中的值过滤选择的值

时间:2018-10-03 03:56:56

标签: mysql

我有一张桌子,如下:

用户

SELECT CustomerID,Cashier, OrderDate,SUM(Total) as totalprice
FROM SalesandReports
GROUP BY CustomerID, Cashier, OrderDate WITH ROLLUP

和另一个桌子

Access_Control

[id] | [name] | [gender] | [phone]    
1    | David  | M        | 12345678 
2    | Mary   | F        | 18345679 
3    | Joe    | M        | 12845670 
4    | John   | M        | 12345671 
5    | May    | F        | 16355672 

问题:仅使用SQL即可获得如下所示的视图

[company] | [access_allowed]
Company A | gender 
Company A | phone
Company A | name
Company B | name
Company C | gender
Company C | phone

如果需要,可以更改Access_Control表的模式。

这很容易与服务器端语言结合使用,但是仅使用SQL就能做到吗?谢谢!

1 个答案:

答案 0 :(得分:0)

三个月后,我终于能够回答我自己的问题,解决方案虽然有点脏,但可以完成工作并且运行非常快。


第1步:将Access_Control更改为垂直视图

CREATE VIEW `access_control_vertical` AS
    SELECT 
        `access_control`.`company` AS `company`,
        BIT_OR((CASE
            WHEN (`access_control`.`access_allowed` = 'gender') THEN 1
            ELSE 0
        END)) AS `gender`,
        BIT_OR((CASE
            WHEN (`access_control`.`access_allowed` = 'name') THEN 1
            ELSE 0
        END)) AS `name`,
        BIT_OR((CASE
            WHEN (`access_control`.`access_allowed` = 'phone') THEN 1
            ELSE 0
        END)) AS `phone`
    FROM
        `access_control`
    GROUP BY `access_control`.`company`

结果1:

company gender name phone
A       1       1   1
B       0       1   0
C       1       0   1

第2步:用例过滤掉哪个公司可以从用户那里获得哪个参数

CREATE VIEW `filtered_user` AS
    SELECT 
        `access_control_vertical`.`company` AS `company`,
        (CASE
            WHEN (`access_control_vertical`.`gender` = 1) THEN `user`.`gender`
            ELSE 'N/A'
        END) AS `gender`,
        (CASE
            WHEN (`access_control_vertical`.`gender` = 1) THEN `user`.`name`
            ELSE 'N/A'
        END) AS `name`,
        (CASE
            WHEN (`access_control_vertical`.`gender` = 1) THEN `user`.`phone`
            ELSE 'N/A'
        END) AS `phone`
    FROM
        (`user`
        JOIN `access_control_vertical` ON ((1 = 1)))

结果2:

company, gender, name, phone
'A', 'M', 'David', '12345678'
'A', 'F', 'Mary   ', '18345679'
'A', 'M', 'Joe    ', '12845670'
'A', 'M', 'John   ', '12345671'
'A', 'F', 'May    ', '16355672'
'B', 'N/A', 'N/A', 'N/A'
'B', 'N/A', 'N/A', 'N/A'
'B', 'N/A', 'N/A', 'N/A'
'B', 'N/A', 'N/A', 'N/A'
'B', 'N/A', 'N/A', 'N/A'
'C', 'M', 'David', '12345678'
'C', 'F', 'Mary   ', '18345679'
'C', 'M', 'Joe    ', '12845670'
'C', 'M', 'John   ', '12345671'
'C', 'F', 'May    ', '16355672'