简体   繁体   中英

SELECT DISTINCT 2 columns in a INNER JOIN

I'm having a problem with a query for MySQL, i have to get rows with distinct "c.email" AND distinct "pf.cliente_id", I'm doing this code below, but i'm not getting what i want, the "c.email" don't returns DISTINCT

SELECT DISTINCT c.nome as nome, pf.id_cliente as cliente_id
FROM cliente c
INNER JOIN pessoa_fisica pf
ON c.id_cliente = pf.id_cliente
GROUP BY c.email, pf.id_cliente;

I Also tried:

SELECT c.nome as nome, pf.id_cliente as cliente_id
FROM cliente c
INNER JOIN pessoa_fisica pf
ON c.id_cliente = pf.id_cliente
GROUP BY c.email, pf.id_cliente;

Edit

cliente = email( It's not the primary key, is a foreign key and i have it reapeted )

pessoa_fisica = id_cliente ( It's not the primary key, is a foreign key and i have it reapeted )

this query world work for you may be syntax error there because i have not database.

select SUBSTRING_INDEX(full, ' ', 1) AS email ,SUBSTRING_INDEX(full, ' ', -1) AS cliente_id , nome
from 
(SELECT DISTINCT (concat(c.email as email,' ',pf.id_cliente )) as 'full' , c.nome as 'nome'
FROM cliente c
INNER JOIN pessoa_fisica pf
ON c.id_cliente = pf.id_cliente) as temp;

Mysql distinct doesn't allow multiple values, but apply little effort means first concat columns and then apply distinct then break column again. I am setting an example for you.

   Create Table: CREATE TABLE `dupli` (
      `id` int(11) NOT NULL AUTO_INCREMENT,
      `fname` varchar(20) DEFAULT NULL,
      `lname` varchar(20) DEFAULT NULL,
      PRIMARY KEY (`id`)
    ) ENGINE=InnoDB AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;

     insert into dupli (fname,lname) values ('Hitesh', 'mundra'),('Neeraj', 'sharma'),('Kailash','yadav');

     insert into dupli (fname,lname) values ('Hitesh', 'mundra'),('Neeraj', 'sharma'),('Kailash','yadav');

    select id, SUBSTRING_INDEX(name, ' ', 1) AS fname ,SUBSTRING_INDEX(name, ' ', -1) AS lname  from (select  distinct( concat(fname," ",lname) ) as Name, id from dupli) as temp;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM