mysql - 如何在使用 UNION mysql 查询时获取唯一值

标签 mysql

我有2个返回结果的sql查询,都包含契约(Contract)号,现在我想获取契约(Contract)号的唯一值

这是查询

(SELECT contractno, dsignoff FROM campaigns WHERE clientid = 20010490 AND contractno != '' GROUP BY contractno,dsignoff) UNION (SELECT id AS contractno,signoffdate AS dsignoff FROM contract_details WHERE clientid = 20010490) 

例如,如果 union 之前的第一个查询返回两个合约编号为 10 的结果,并且 union 之后的 sql 查询也返回 10,那么我们总共有 3 行,但是因为所有三行的contractno 都是 10 ,我只需要返回一行,这可能吗?

最佳答案

您可以将当前请求放入临时表中,并在此表上执行选择:

SELECT
  *
FROM
  (
   /* Your request goes here */
    SELECT 
      contractno, 
      dsignoff 
    FROM 
      campaigns 
    WHERE 
      clientid = 20010490 AND contractno != '' 
    GROUP BY 
      contractno,dsignoff
    UNION
    SELECT 
      id AS contractno,
      signoffdate AS dsignoff
    FROM 
      contract_details 
    WHERE clientid = 20010490) 
  ) AS tmp
GROUP BY
  tmp.contractno

(但是你确定不能用连接做你想做的事吗?)

关于mysql - 如何在使用 UNION mysql 查询时获取唯一值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3061802/

相关文章:

php - ORDER MySQL 结果按日期并使用 LIKE

mysql - 如何根据mysql中的另一个表更新表?

mysql - 在 MySQL 4.1 中选择特定类型的列

python - Qt/QSql查询 : Binary data is interpreted as string when binding to BLOB field

python - flake8 在过滤器子句中提示 bool 比较 "=="

java - 从数据库获取日期并在 Java 中进行比较

MySQL : Why is comparing primary key to a randomly generated number not using the index?

PHP MySQL 下拉框

PHP MySQL 数据库图像切换器

mysql - 如何合并列中具有相同值的两个表