删除空格后选择唯一数据

时间:2014-12-19 19:43:50

标签: php mysql removing-whitespace

我有以下MySQL声明:

SELECT registration FROM
  (SELECT registration FROM installs
      WHERE customer_id = :id1
  UNION SELECT registration FROM services
      WHERE customer_id = :id2
  UNION SELECT registration FROM deinstalls
      WHERE customer_id = :id3)
AS vehicles

我需要从多个表中选择唯一的“注册”,这个语句几乎完美无缺。

选择AB01 CDEaB01 cdE作为一个项目,但AB01CDE / aB01cdE被选为不同的项目。

我尝试在第一个REPLACE周围使用registration来删除选择唯一项目时的空格。

3 个答案:

答案 0 :(得分:1)

REPLACE()应该有效。你做到了吗?

SELECT DISTINCT REPLACE(registration, ' ', '') as Registration
FROM (SELECT registration
      FROM installs
      WHERE customer_id = :id1
      UNION ALL
      SELECT registration
      FROM services
      WHERE customer_id = :id2
      SELECT registration
      FROM deinstalls
      WHERE customer_id = :id3
     ) v;

分隔字符也可能不是空格,在这种情况下,这不起作用。

答案 1 :(得分:0)

我想这可能就是你在寻找什么?

SELECT registration FROM customers WHERE customer_id in
  (SELECT registration AS installs_registration FROM installs WHERE customers.customer_id = installs.id,
  SELECT registration AS services_registration FROM services  WHERE customers.customer_id = services.id,
  SELECT registration AS deinstalls_registration FROM deinstalls WHERE customers.customer_id = deinstalls.id)

答案 2 :(得分:0)

您有两种选择。第一个是将DISTINCT添加到REPLACE上的第一个registration

SELECT DISTINCT REPLACE(registration, ' ', '') FROM (
  ... your UNION queries
)
AS vehicles

第二种是在每个子查询中使用REPLACE; UNION确保您获得明显的结果:

SELECT registration FROM (
  SELECT REPLACE(registration, ' ', '') AS registration
    FROM installs
    WHERE customer_id = :id1
  UNION SELECT REPLACE(registration, ' ', '')
    FROM services
    WHERE customer_id = :id2
  UNION SELECT REPLACE(registration, ' ', '')
    FROM deinstalls
   WHERE customer_id = :id3
)
AS vehicles