简体   繁体   English

mysql中具有相同表名的相同列名称

[英]same colum name with different table id in mysql

tables

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 is key between them. person_id是它们之间的关键。

So my question how can retrive customers firstname and last name, waiter firstname and lastname via 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

if I execute this query, I get the following error: 如果执行此查询,则会出现以下错误:

customer_Fist_name NULL,Customer_LastName NULL, WaiterFirstName NULL, Waiter_LastName NULL,

You want to do JOIN 's two times on the same table but with different values (customer's data and waiter's data), but you just use a JOIN once and give both conditions there. 您想要在同一张表上执行两次JOIN但是使用不同的值(客户数据和服务员数据),但是您只需要使用一次JOIN并在此处给出两个条件。

To fix this, your have to JOIN the phs_people -Table twice like this: 要解决此问题,您必须像这样两次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
...

and then select the correct data like this: 然后选择正确的数据,如下所示:

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: With this query, you should still get multiple NULL -Values, that's because half of your phs_sales -Table is filled with empty fields... PS:有了这个查询,你还是应该得到多个NULL -值,这是因为你的一半phs_sales -表填充空字段...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM