如何在MySql中查询引用自身的表?

时间:2015-02-03 14:21:43

标签: mysql sql

我的表格Customers包含字段customer_idfirst_namelast_namereferred_by

我想要的是显示被推荐客户的全名和推荐人的全名。

例如我想要这样的东西:

id | first_name | last_name | referred_by
1  |  first1    |  last1    |    NULL
2  |  first2    |  last2    |     1
3  |  first3    |  last3    |     2

oupout应该是:

customer's name   | referred by
first2 last2      | first1 last1
first3 last3      | first2 last2

通常我会创建一个名为references的表并在那里存储引用,但我无法修改数据库。

我想象的是:

SELECT 
     CONCAT(firstname, ' ', lastname) AS 'Customer''s Name', 
     CONCAT(firstname, ' ', lastname) AS 'Referred By '
FROM customer
WHERE 'Customer''s Name'.refferedby = 'Referred By'.customerno;

感谢您的帮助。

3 个答案:

答案 0 :(得分:3)

如果refer_by列包含来自customer表的id值,那么它将是这样的:

select concat(c.firstname,' ',c.lastname) customer
     , concat(r.firstname,' ',r.lastname) referred_by_customer
from customer c
     left join customer r on r.customer_id = c.referred_by

答案 1 :(得分:0)

使用加入。

SELECT 
     CONCAT(c1.firstname, ' ', c1.lastname) AS 'Customer''s Name', 
     CONCAT(c2.firstname, ' ', c2.lastname) AS 'Referred By '
FROM customer c1 join customer c2 = c1.id = c2.referred_by

答案 2 :(得分:0)

这个连接解决方​​案几乎就是我想要的!必须反转c2和c1字段,并且连接上也存在语法错误,因此正确的查询是:

SELECT 
     CONCAT(c1.firstname, ' ', c1.lastname) AS 'Customer''s Name', 
     CONCAT(c2.firstname, ' ', c2.lastname) AS 'Referred By '
FROM customer c1 join customer c2 on c1.referredby = c2.customerno;

左连接的解决方案也给了我所有未被推荐的客户(这对我来说没用,查询的目的是找到被推荐的客户)。

但是我得到了相同的结果:

 select concat(c.firstname,' ',c.lastname) 'Customer''s Name',
        concat(r.firstname,' ',r.lastname) 'Referred By ' 
 from customer c, customer r 
 where r.customerno = c.referredby;

有趣的是,我一直认为表别名用于最小化写入,而不是实际区分同一个表的不同调用。

使用不同的写作是否是相同的查询,或者我缺少什么?