我有一些表,我试图从中获取数据。我需要将cust和emp表链接到销售表。然后,从person表中获取cust和emp的名称。
我被困了
数据如下:
表SALES
+--------+--------+-------+-------+
| saleID | custID | empID | total |
|--------+--------+-------+-------|
| 1 | 1 | 1 | 3.00 |
|--------+--------+-------+-------|
| 2 | 2 | 3 | 6.00 |
|--------+--------+-------+-------|
| 3 | 3 | 1 | 9.00 |
|--------+--------+-------+-------|
| 4 | 2 | 2 | 2.00 |
|--------+--------+-------+-------|
| 5 | 3 | 3 | 1.00 |
|--------+--------+-------+-------+
表cust
+--------+---------+----------+
| custID | company | personID
+--------+---------+----------+
| 1 | comp1 + 2 |
+--------+---------+----------+
| 2 | comp2 + 4 |
+--------+---------+----------+
| 3 | comp3 + 6 |
+--------+---------+----------+
表emp
+--------+----------+----------+
| custID | username | personID |
+--------+----------+----------+
| 1 | emp1 | 1 |
+--------+----------+----------+
| 2 | emp2 | 3 |
+--------+----------+----------+
| 3 | emp3 | 5 |
+--------+----------+----------+
表person
+----------+------+
| personID | name |
+----------+------+
| 1 | per1 |
+----------+------+
| 2 | per2 |
+----------+------+
| 3 | per3 |
+----------+------+
| 4 | per4 |
+----------+------+
| 5 | per5 |
+----------+------+
| 6 | per6 |
+----------+------+
我想查询给我这个:
+--------+--------+----------+-------+---------+-------+
| saleID | custID | custName | empID | empName | total |
+--------+--------+----------+-------+---------+-------+
| 1 | 1 | per2 | 1 | per1 | 3.00 |
+--------+--------+----------+-------+---------+-------+
| 2 | 2 | per4 | 3 | per5 | 6.00 |
+--------+--------+----------+-------+---------+-------+
| 3 | 3 | per6 | 1 | per1 | 9.00 |
+--------+--------+----------+-------+---------+-------+
| 4 | 2 | per4 | 2 | per3 | 2.00 |
+--------+--------+----------+-------+---------+-------+
| 5 | 3 | per6 | 3 | per5 | 1.00 |
+--------+--------+----------+-------+---------+-------+
答案 0 :(得分:1)
简单的JOIN应该可以解决问题:
SELECT
a.saleID,
b.custID,
p1.name as custName,
c.empID,
p2.name as empName,
a.total
FROM SALES a
JOIN cust b
ON a.custID = b.custID
JOIN emp c
ON c.custID = a.custID AND c.empID = a.empID
JOIN person p1
ON p1.personID = b.personID
JOIN person p2
ON p2.personID = c.personID
ORDER BY saleID
答案 1 :(得分:0)
试试这个:
select a.saleID, a.custID, d.name as custName,a.empID,e.nname as empName,
a.total
from
sales a
left join
cust b
on a.custID = b.custID
left join
emp c
on a.empID = C.custID
left join
person d
on b.personID = d.personID
left join
person e
on c.personID = e.personID
如有任何疑问,请与我联系。