SELECT两个表区别。 MySQL的

时间:2014-05-28 13:04:40

标签: php mysql select distinct

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

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 "
          ); 

谢谢!

3 个答案:

答案 0 :(得分:3)

您可以使用union

select id_product
from tb_compare
union
select id_product
from tb_product_field;

请注意,union会删除列表中的重复行,因此不需要distinct。在这种情况下,一行只包含一个值。

答案 1 :(得分:0)

首先加入两个表,然后执行子查询:

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
     )

答案 2 :(得分:0)

我找到了一个解决方案,我尝试将GROUP BY改为ORDER BY,然后删除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 "
      );

感谢所有人。