选择3列到1没有联合

时间:2017-09-09 15:09:12

标签: mysql

我尝试在不使用union(需要系统)的情况下为一列选择三列(TEXT - 相同类型),但我无法以正确的方式思考。

select count(distinct(r)) as count 
from (
    select column1 as r from Table1
    union all
    select column2 as r from Table1
    union all
    select column3 as r from Table1
) a

这是原始查询, 我尝试使用CONCAT和COALESCE,但这不是我想要的。 我不想将两个字符串合并为一个, 我希望所有选择行都在同一列中。

例如 - example - img

3列 - to,cc和bcc(电子邮件收件人)。 我想知道我发送电子邮件的人数。 没有双重电子邮件(每个人都可以在任何列上)

感谢您的帮助! 我很感激。

3 个答案:

答案 0 :(得分:1)

使用SharedPreferences sharedPref = PreferenceManager.getDefaultSharedPreferences(this) String defaultValue = "-1"; // assign some meaningful default value int amountPlayers = Integer.parseInt(sharedPref.getString("NUM_OF_PLAYERS_PREF_KEY", defaultValue));

COUNT(DISTINCT ...)

更好:因为你在外部查询上运行SELECT COUNT(DISTINCT email) FROM ( SELECT DISTINCT firstColumn AS email FROM table UNION SELECT DISTINCT secondColumn AS email FROM table UNION SELECT DISTINCT thirdColumn AS email FROM table) AS Recipients ,所以不要浪费时间在内部查询中执行此操作:

DISTINCT

请参阅示例小提琴:http://sqlfiddle.com/#!9/edda57/10

答案 1 :(得分:0)

只需在一个concat :)示例中使用别名:

SELECT CONCAT(to, cc, bcc, year) as new_colum_mailing FROM `mailing` .. WHERE    ...

答案 2 :(得分:0)

没有UNION,但更加丑陋。我自己加入表并获取前3 * TABLE_LENGTH行,因为我需要处理三个不同的列。

SELECT count(DISTINCT if(rank<=@size, recipient, if(rank<=2*@size,cc,bcc)))
FROM
  (SELECT (@rank:=@rank+1) AS rank,
          s1.recipient,
          s1.cc,
          s1.bcc
   FROM sent AS s1
   JOIN sent AS s2) AS multi,

  (SELECT @rank:=0) AS dummy1,

  (SELECT @size:=
     (SELECT count(1)
      FROM sent)) AS dummy2
WHERE rank <= 3*@size

小提琴:http://sqlfiddle.com/#!9/14ac8a/14/0