我无法从数据库中选择数据。
下面给出了我的表格结构
客户表
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
如果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
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
尝试在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