Mysql从两个表中获取数据而不重复

时间:2015-07-16 15:57:32

标签: php mysql join

我有两张桌子

table customers
cust_id  cust_name    cust_age    cust_level
-----    -----------  --------    ----------
1         raj           19             2  
2         ravi          22             3  
3         mani          20             4  
4         prem          41             1
5         kumar         34             2  



table emails
cont_id  cust_id     email_id          
-----    ----------  --------          
1         4           ravi@hi.com        
2         1           man@ji.com
3         4           ravee@ko.com
4         5           thee@lo.com
5         3           ras@ki.com

现在我想获取emails.email id喜欢的客户列表' r%'和list应该是customers.cust_level的顺序ASC不会有重复

my required ouptput is 

cust_id       cust_name    email_id      cust_level
-------       --------     --------      ----------
4             prem         ravi@hi.com     1
3             mani         ras@ki.com      4

请仔细查看表格电子邮件,我们有两个客户ID为4的电子邮件ID,但我们只需要一个customer_id 4条目[即不需要重复的客户ID条目] 可以使用任何类型的连接,不同的,组...

2 个答案:

答案 0 :(得分:0)

使用两者中存在的列连接两个表,然后返回要显示的列。

SELECT c.cust_id, cust_name, email_id, cust_level
FROM customers c
LEFT JOIN emails e USING (cust_id)

答案 1 :(得分:0)

myUserID

应该这样做,如果您需要一行中一位客户的所有电子邮件,请添加另一个字段SELECT c.cust_id as custi_id, c.cust_name as cust_name, e.email_id as email_id, c.cust_level as cust_level FROM customer c JOIN emails e ON (c.cust_id = e.cust_id) WHERE e.email_id LIKE 'r%' GROUP BY c.cust_id ORDER By cust_level