UNION在MYSQL中有三种不同的SELECT

时间:2014-12-01 11:30:42

标签: mysql select union

我有一个名为people的MYSQL表,其列为:id | firstname | lastname | birthdate | phone。

我对MYSQL很新,我正在尝试UNION几个SELECT,以便结果看起来如下:

  • 只能显示前20个结果

  • 第一个SELECT标准是组合firstname + lastname + birthdate:WHERE(birthdate =“1980-01-01”)AND((firstname LIKE“%john%”)AND(lastname LIKE“%smith %“))

  • 第二个SELECT标准是组合firstname + lastname:WHERE(firstname LIKE“%john%”)AND(lastname LIKE“%smith%”)

  • 第三个SELECT标准是通过电话:WHERE phone =“0123456”

  • 输出结果实际上必须有3列:order | id | type;其中“order”和“type”是别名列

  • 导出的id必须是唯一的:如果同一个id来自所有3个SELECT(或来自多个SELECT),那么它必须在输出表中只出现一次

  • 列“order”必须为第一个SELECT的结果值为1,第二个SELECT的值为2,最后一个SELECT的值为3

  • 如果相同的id值来自多个SELECT,则其行必须具有最高的订单值;从第一个SELECT

  • 开始,最高阶可能为1
  • 别名列“type”必须如下所示:如果id来自第一个SELECT,则其类型值为“~sirstname + lastname + birthdate~”;如果id来自第二个SELECT,则其类型值为“~sirstname + lastname~”;最后如果一个id来自第三个SELECT,它的类型值是“~phone~”

  • 如果相同的id值来自多个SELECT,则“type”别名列上的值必须是找到该id的SELECT之间的连接(例如,如果相同的id导致所有3 SELECT查询然后“type”列上的值将是“~sirstname + lastname + birthdate ~~ firstname + lastname ~~ phone~”)

是否有可能实现这样的输出?

2 个答案:

答案 0 :(得分:0)

这是使用CASE语句的东西。由于您的订单类型声明,我认为您会因工会声明陷入困境。希望我已经理解了你所追求的东西 - 如果你发布样本数据会容易得多!无论如何,即使这并不是你想要的,你也会得到这个想法......

[编辑]我不认为你需要独特的,但我不认为它会伤害,或者......

 SELECT DISTINCT 
        CASE WHEN birthdate='1980-01-01' 
                AND firstname LIKE '%john%' AND lastname LIKE '%smith%'
             THEN 1
             WHEN firstname LIKE '%john%' AND lastname LIKE '%smith%'
             THEN 2
             WHEN phone='0123456'
             THEN 3
        END AS outputorder, -- avoid confusion of using an SQL keyword as a column name,
           id,

           CONCAT(
              CASE 

     WHEN birthdate='1980-01-01' 
            AND firstname LIKE '%john%' AND lastname LIKE '%smith%'
            THEN CONCAT('~',firstname,'+',lastname,'+','~')
          END ,

         CASE WHEN firstname LIKE '%john%' AND lastname LIKE '%smith%'
             THEN CONCAT('~',firstname,'+',lastname,'~')
         END ,
         CASE WHEN phone='0123456'
              THEN CONCAT('~',phone,'~')
         END 
       ) -- end the concat
       AS outputtype
FROM

     mytable
WHERE
   ( birthdate='1980-01-01' 
   AND firstname LIKE '%john%' AND lastname LIKE '%smith%')
OR
   (firstname LIKE '%john%' AND lastname LIKE '%smith%')
OR
    phone='0123456'
ORDER by 1,2 LIMIT 20

答案 1 :(得分:0)

最后我做了类似的事情并且工作得很好:



SELECT MIN(`ord`) AS `order` , `id` , GROUP_CONCAT(`spec`) as `type` FROM (
SELECT "1" AS `ord` , `id` , "~firstname+lastname+birthdate~" AS `spec` FROM `people` WHERE (`birthdate` = "1986-04-02") AND (`lastname` LIKE "%smith%") AND (`firstname` LIKE "%john%")
UNION
SELECT "2" AS `ord` , `id` , "~firstname+lastname~" AS `spec` FROM `people` WHERE (`lastname` LIKE "%smith%") AND (`firstname` LIKE "%john%")
UNION
SELECT "3" AS `ord` , `id` , "~phone~" AS `spec` FROM `people` WHERE (`phone`="0123456")
) final
GROUP BY final.`id`
ORDER BY `order` ASC 
LIMIT 20




感谢mlinth的替代选择......