How to select two columns having different conditions for each colums from MySQL Database?

拟墨画扇 提交于 2019-12-02 13:06:28

lets say i want to select two columns. Column one should contain all the names before 2019-09-11 and column two should contain all the names after 2019-09-11. So basically there would be two different where conditions for the two columns.

Little bit wierd request for a RDMS.
Anyhow the query below is not tested but i would use two sub queries (derived tables ) with a MySQL user variable to generate a row_number which you can use to join later..

note As SQL is orderless i am assuming here you don't care about a sort in the columns.

SELECT 
 *
FROM (
  SELECT 
    *
    , (@row_num1 := @row_num1 + 1) AS row_number    
  FROM  
   t  
  CROSS JOIN (SELECT @row_num1 := 0) AS init_user_param                  
  WHERE 
   `timestamp` < '2019-09-11'  
) AS left_column
LEFT/RIGHT JOIN (
  SELECT 
    *
    , (@row_num2 := @row_num2 + 1) AS row_number
  FROM  
   t
  CROSS JOIN (SELECT @row_num2 := 0) AS init_user_param                  
  WHERE 
   `timestamp` > '2019-09-11'  
) AS right_column
ON
 left_column.row_number = right_column.row_number

Comment of Madhur Bhaiya
This will require a FULL JOIN; because we dont know which side has more rows.

Very true you would need to use LEFT JOIN if the left column contains more records. And RIGHT JOIN when the right column contains more records.

As this is a wierd request anyway i would suggest using programming language or MySQL's PREPARE/EXECUTE to build the query dynamic so FULL JOIN emulation is not required..

Warning using EXECUTE/PREPARE in MySQL to generate dynamic SQL is complex if you never seen or usaged it before...

Query

SET @sql = CONCAT("
SELECT 
 *
FROM (
  SELECT 
    *
    , (@row_num1 := @row_num1 + 1) AS row_number
  FROM  
   t  
  CROSS JOIN (SELECT @row_num1 := 0) AS init_user_param                  
  WHERE 
   `timestamp` < '2019-09-11'  
) AS left_column
",

(
  SELECT 
   CASE
    WHEN left_column_count > right_column_count
    THEN 'LEFT JOIN'
    ELSE 'RIGHT JOIN' 
   END
  FROM (
    SELECT
         SUM(`timestamp` < '2019-09-11') AS left_column_count
       , SUM(`timestamp` > '2019-09-11') AS right_column_count
    FROM 
     t
  ) AS t
)                 

," (
  SELECT 
    *
    , (@row_num2 := @row_num2 + 1) AS row_number
  FROM  
   t
  CROSS JOIN (SELECT @row_num2 := 0) AS init_user_param                  
  WHERE 
   `timestamp` > '2019-09-11'  
) AS right_column
ON
 left_column.row_number = right_column.row_number
");


SELECT @sql; 
PREPARE s FROM @sql;
EXECUTE s;

see demo

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!