我无法使用mysql从内部联接中选择数据库中的数据

时间:2014-10-21 10:21:15

标签: php mysql

我无法从数据库中选择数据。

我的表格结构如下:

客户表

id      name
10      geetha

客户国家/地区表

id    cust_id  country

1       10      6
2       10      16

我得到了这样的结果

customer name      country


geetha             6
geetha             16

但我想只获得一次客户数据,即不再重复。

customer name      country


geetha             6

我的查询是

SELECT customer.name,customer.id,customer_country.country_id, customer_country.cust_id
    FROM customer
    INNER JOIN customer_country on customer.id = customer_country.cust_id

3 个答案:

答案 0 :(得分:2)

如果customer_country表中有重复项,则需要选择其中一个。以下是使用max()的一种方法:

select c.name, max(cc.country_id)
from customer c inner join
     customer_country cc
     on c.id = cc.cust_id
group by c.name;

如果您希望列表中包含所有这些内容,请使用group_concat()

select c.name, group_concat(cc.country_id) as countries
from customer c inner join
     customer_country cc
     on c.id = cc.cust_id
group by c.name;

答案 1 :(得分:0)

仅限第一条记录,请申请结束:限制1

    SELECT customer.name,customer.id,customer_country.country_id,
    customer_country.cust_id from customer 
    inner join customer_country on customer.id= customer_country.cust_id limit 1

答案 2 :(得分:0)

尝试这个我在customer_country.cust_id

之前添加distinct
SELECT customer.name,customer.id,customer_country.country_id, distinct customer_country.cust_id
FROM customer
INNER JOIN customer_country on customer.id = customer_country.cust_id