SELECT两个表区别。 MySQL的

SELECT两个表区别。  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!!

我有2个不同的表,每个表都有一个名为id_product的列。 如何在两个表中获取id_field的DISTINCT值? p>

  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“
);  
  code>  pre> 
 
 

谢谢!! p> div>

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.

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
     )

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.