MYSQL从3个表中获取信息

时间:2013-04-25 21:38:08

标签: php mysql sql

我有3张桌子。第一个包含customer_group_idaccount_number,将每个组链接到一个帐户。第二个包含customer_idcustomer_group_id,将每个客户链接到一个客户组,第三个包含客户ID的客户描述。

我想获取帐户customer_group中所有客户的客户信息。我使用的语法如下:

SELECT *, CONCAT(c.firstname, ' ', c.lastname) AS name, cgd.name AS customer_group 
 FROM customer c 
 LEFT JOIN customer_group_description cgd 
 LEFT JOIN customer_group cg 
 ON (c.customer_group_id = cgd.customer_group_id) 
 WHERE cg.account_number = '1'

拜托,非常感谢任何帮助。

customer_group:
--------------------------------------
| customer_group_id | account_number |
--------------------------------------
| 1                 | 1              |
| 2                 | 1              |
| 3                 | 1              |
--------------------------------------

customer_group_description
--------------------------------------
| customer_group_id | name           |
--------------------------------------
| 1                 | group1         |
| 2                 | group2         |
| 3                 | group3         |
--------------------------------------

customer
-----------------------------------------------
| firstname   | lastname  | customer_group_id |
-----------------------------------------------
| john        | smith     |  1                |
| black       | smith     |  1                |
| gold        | smith     |  2                |
| bob         | dylan     |  3                |
-----------------------------------------------

我希望这有助于更好地澄清我的问题。我们的想法是让所有用户都在帐号1下。

谢谢。

1 个答案:

答案 0 :(得分:1)

转到UNIONUNION ALL的MySQL手册并阅读此问题:What is the difference between UNION and UNION ALL?