Malika Harkati
Malika Harkati

Reputation: 21

SELECT Distinct FROM two tables . MySQL

I have 2 different tables that each have a column called id_product. How can I get the DISTINCT values of id_field across both tables?

tb_compare
-id_product

tb_product_field 
-id_product
-id_field


 $qasql1 = mysql_query("SELECT c1.*,
           c2.DISTINCT(id_field) FROM  tb_compare AS c1 
           INNER JOIN tb_product_field AS c2 ON c1.id_product=c2.id_product 
           WHERE c1.compareSession = '$sessionID'  ORDER BY c1.compareID Desc "
          ); 

Thanks!!

Upvotes: 1

Views: 2433

Answers (3)

Malika Harkati
Malika Harkati

Reputation: 21

I found a solution, i try to put GROUP BY instead to ORDER BY,and i remove DINSTINCT.

$qasql1 = mysql_query("SELECT c1.*,
       c2.id_field FROM  tb_compare AS c1 
       INNER JOIN tb_product_field AS c2 ON c1.id_product=c2.id_product 
       WHERE c1.compareSession = '$sessionID' GROUP BY c1.compareID Desc "
      );

thanks to everyone.

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270301

You can use union:

select id_product
from tb_compare
union
select id_product
from tb_product_field;

Note that union removes duplicate rows in a list, so distinct is not necessary. In this case, a row consists only of a single value.

Upvotes: 3

Alex W
Alex W

Reputation: 38233

JOIN both of the tables first, and then do a subquery:

SELECT DISTINCT id_field FROM
    (SELECT * FROM tb_compare AS c1 
        INNER JOIN tb_product_field AS c2 
        ON c1.id_product=c2.id_product 
        WHERE c1.compareSession = '$sessionID' 
        ORDER BY c1.compareID Desc
     )

Upvotes: 0

Related Questions