表
person_id (primary key)
phs_people (person_id,first_name,last_name)
phs_cutomers (person_id,company_name)
phs_waiters (person_id,commission)
person_id是他们之间的关键。
所以我的问题是如何通过person_id来检索客户名字和姓氏,服务员名字和姓氏?
SELECT
c.first_name AS customer_Fist_name,
c.last_name AS Customer_LastName,
c.first_name AS WaiterFirstName,
c.last_name AS Waiter_LastName,
invoice_number, amount_tendered, sale_time, DATE_FORMAT( sale_time, '%d-%m-%Y' ) AS sale_date, phs_sales.sale_id AS sale_id, SUM( item_unit_price * quantity_purchased * ( 1 - discount_percent /100 ) ) AS amount_due
FROM (
phs_sales
)
LEFT JOIN phs_people c ON c.person_id = phs_sales.customer_id
AND person_id = phs_sales.waiter_id
JOIN phs_sales_items ON phs_sales_items.sale_id = phs_sales.sale_id
LEFT JOIN (
SELECT sale_id, SUM( payment_amount ) AS amount_tendered
FROM phs_sales_payments
WHERE payment_type <> 'Check'
GROUP BY sale_id
) AS payments ON payments.sale_id = phs_sales.sale_id
GROUP BY sale_id
ORDER BY sale_time DESC
LIMIT 25
如果我执行此查询,则会收到以下错误:
customer_Fist_name NULL,Customer_LastName NULL, WaiterFirstName NULL, Waiter_LastName NULL,
答案 0 :(得分:0)
你想在同一张桌子上做JOIN
两次但有不同的价值(客户的数据和服务员的数据),但你只需要JOIN
1}}一次并在那里给出两个条件。
要解决此问题,您必须JOIN
phs_people
- 表格两次这样:
...
LEFT JOIN phs_people AS c1 ON c1.person_id = phs_sales.customer_id
LEFT JOIN phs_people AS c2 ON c2.person_id = phs_sales.waiter_id
...
然后选择正确的数据:
SELECT
c1.first_name AS customer_Fist_name,
c1.last_name AS Customer_LastName,
c2.first_name AS WaiterFirstName,
c2.last_name AS Waiter_LastName,
...
PS:使用此查询,您仍然应该获得多个NULL
- 值,因为phs_sales
- 表的一半用空字段填充...