duanjie3267
2014-05-28 13:04
浏览 39
已采纳

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!!

图片转代码服务由CSDN问答提供 功能建议

我有2个不同的表,每个表都有一个名为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条回答 默认 最新

  • dongshang6790 2014-05-28 13:08
    已采纳

    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.

    打赏 评论
  • doupo1890 2014-05-28 13:11

    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
         )
    
    打赏 评论
  • douzai3399 2014-05-29 07:44

    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.

    打赏 评论

相关推荐 更多相似问题