如何使用CURDATE()作为列名

时间:2018-04-18 05:23:27

标签: mysql sql

这是我的查询(它不起作用。)

SELECT *
FROM main_table mt
LEFT JOIN table1 t1
    ON mt.PK = t1.PK
LEFT JOIN table2 t2
    ON mt.PK = t2.PK
...
LEFT JOIN table11 t11
    ON mt.PK = t11.PK;

我希望看到这样的。

enter image description here

1 个答案:

答案 0 :(得分:1)

这确实是一项要求,最好通过使用您的视图技术来处理,例如:类似PHP或Java的东西。在这种应用程序语言中,获取结果集并按照您希望的方式格式化它相对容易。

话虽如此,如果你在MySQL中需要你的确切输出,它是可能的,但有一个相当大的联合查询:

SELECT
    c1, c2, c3, c4, c5, c6, c7
FROM
(
    SELECT 
        DATE_FORMAT(CURDATE(), '%Y-%m-%d') AS c1,
        DATE_FORMAT(CURDATE()-1, '%Y-%m-%d') AS c2,
        DATE_FORMAT(CURDATE()-2, '%Y-%m-%d') AS c3,
        DATE_FORMAT(CURDATE()-3, '%Y-%m-%d') AS c4,
        DATE_FORMAT(CURDATE()-4, '%Y-%m-%d') AS c5,
        DATE_FORMAT(CURDATE()-5, '%Y-%m-%d') AS c6,
        DATE_FORMAT(CURDATE()-6, '%Y-%m-%d') AS c7,
        0 AS position
    FROM dual
    UNION ALL
    SELECT
        (SELECT CAST(SUM(last_access_date > CURDATE() AND last_access_date < CURDATE()+1) AS CHAR(50))),
        (SELECT CAST(SUM(last_access_date > CURDATE()-1 and last_access_date < CURDATE()) AS CHAR(50))),
        (SELECT CAST(SUM(last_access_date > CURDATE()-2 and last_access_date < CURDATE()-1) AS CHAR(50))),
        (SELECT CAST(SUM(last_access_date > CURDATE()-3 and last_access_date < CURDATE()-2) AS CHAR(50))),
        (SELECT CAST(SUM(last_access_date > CURDATE()-4 and last_access_date < CURDATE()-3) AS CHAR(50))),
        (SELECT CAST(SUM(last_access_date > CURDATE()-5 and last_access_date < CURDATE()-4) AS CHAR(50))),
        (SELECT CAST(SUM(last_access_date > CURDATE()-6 and last_access_date < CURDATE()-5) AS CHAR(50))),
        1
    FROM MYTABLE
) t
ORDER BY position;

我没有在您面前提供您的确切数据,但我设法设置了具有虚拟总和值的演示,这就是输出的样子:

enter image description here

Demo