我有两张桌子:
mysql> explain Customers
-> ;
+------------------------+-------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+------------------------+-------------+------+-----+---------+-------+
| customerNumber | int(11) | NO | PRI | NULL | |
| customerName | varchar(50) | NO | | NULL | |
| contactLastName | varchar(50) | NO | | NULL | |
| contactFirstName | varchar(50) | NO | | NULL | |
| phone | varchar(50) | NO | | NULL | |
| addressLine1 | varchar(50) | NO | | NULL | |
| addressLine2 | varchar(50) | YES | | NULL | |
| city | varchar(50) | NO | | NULL | |
| state | varchar(50) | YES | | NULL | |
| postalCode | varchar(15) | YES | | NULL | |
| country | varchar(50) | NO | | NULL | |
| salesRepEmployeeNumber | int(11) | YES | | NULL | |
| creditLimit | double | YES | | NULL | |
+------------------------+-------------+------+-----+---------+-------+
13 rows in set (0.00 sec)
我的另一张桌子是:
mysql> explain Employees;
+----------------+---------------+------+-----+---------+-------+
| Field | Type | Null | Key | Default | Extra |
+----------------+---------------+------+-----+---------+-------+
| employeeNumber | int(11) | NO | PRI | NULL | |
| lastName | varchar(50) | NO | | NULL | |
| firstName | varchar(50) | NO | | NULL | |
| extension | varchar(10) | NO | | NULL | |
| email | varchar(100) | NO | | NULL | |
| officeCode | varchar(10) | NO | | NULL | |
| reportsTo | int(11) | YES | | NULL | |
| jobTitle | varchar(50) | NO | | NULL | |
| salesGoal | decimal(10,0) | YES | | NULL | |
+----------------+---------------+------+-----+---------+-------+
9 rows in set (0.00 sec)
我正在尝试编写一个视图,以限制销售代表仅查看他们在系统中输入的客户。我遇到的问题是销售代表用户名与其电子邮件地址相同。我的where子句有问题,允许他们在登录时查看他们的客户。
到目前为止,我的观点将适用于:
SELECT
cu.customerNumber AS ID,
concat(cu.contactFirstName,_utf8' ',cu.contactLastName) AS Name,
concat(cu.addressLine1,_utf8' ',cu.addressLine2) AS Address,
cu.postalCode AS 'Zip Code',
cu.phone AS Phone,
cu.city AS City,
cu.country AS Country
FROM
Customers cu
JOIN Employees s on (cu.salesRepEmployeeNumber = s.employeeNumber)
WHERE employeeNumber = 123456;
我一直试图使用像
这样的东西SUBSTRING_INDEX(user(), '@', 1)
获取用户名,但我不确定如何将其与Employees表中的电子邮件列相匹配。我是否正确尝试将其与另一个子串匹配?类似的东西:
SELECT
cu.customerNumber AS ID,
concat(cu.contactFirstName,_utf8' ',cu.contactLastName) AS Name,
concat(cu.addressLine1,_utf8' ',cu.addressLine2) AS Address,
cu.postalCode AS 'Zip Code',
cu.phone AS Phone,
cu.city AS City,
cu.country AS Country
FROM
Customers cu
JOIN Employees s on (cu.salesRepEmployeeNumber = s.employeeNumber)
WHERE SUBSTRING_INDEX(user(), '@', 1) =
(SELECT SUBSTRING_INDEX(email, '@', 1) FROM Employees);
我可能会比这更难做到这一点,而且我确定我错过了一些简单的事情!
提前致谢!
答案 0 :(得分:2)
我认为这会做你想做的事情:
WHERE SUBSTRING_INDEX(user(), '@', 1) = SUBSTRING_INDEX(s.email, '@', 1)
不应该需要子查询。