MySQL,检查每列的所有行是否具有相同的值

时间:2019-05-22 08:29:18

标签: mysql

我的一个朋友想要检查表中每一列的所有行是否具有相同的值。 如果是这样,则打印该值。 否则,只需输出一个空字符串或null或其他内容即可。

想象一下这个表,例如:

+--------+----------+-----+
|  Name  | Lastname | Age |
+--------+----------+-----+
| Peter  | White    | 30  |
| Marry  | Jane     | 30  |
| John   | Doe      | 30  |
+--------+----------+-----+

所需查询的结果将输出以下内容:

+--------+----------+-----+
|  Name  | Lastname | Age |
+--------+----------+-----+
|  NULL  |   NULL   | 30  |
+--------+----------+-----+

我试图创建一个函数,该函数将获取给定表的列,遍历每个列名并执行查询。但是由于我不熟悉Mysql,所以我显然错过了一些东西,因此我不知道如何实现我在这里想要做的事情。

DROP PROCEDURE IF EXISTS test;

DELIMITER //

create procedure test()
begin
    declare i int(11);
    declare col_name varchar(50);
    declare num_rows int(11);
    DECLARE col_names CURSOR FOR
        SELECT column_name
        FROM information_schema.columns
        WHERE table_name='name_of_my_table' and table_schema='name_of_db'; 

    select FOUND_ROWS() as num_rows;
    set i = 1;
    open col_names;
        the_loop: LOOP

           IF i > num_rows THEN
                CLOSE col_names;
                LEAVE the_loop;
            END IF;

            FETCH col_names 
            INTO col_name;     

            -- Here I would like to perform a query for each column
            select count(*), col_name from name_of_my_table group by col_name;
            -- Then I was thinking of making an if/ else condition to check 
            -- if I get more than 1 result per column, implying that                 
            -- not all rows have the same value for this column.

            SET i = i + 1;  
        END LOOP the_loop;

    CLOSE col_names;
END//

DELIMITER ;

call test;

输出的结果是找到的最后一列的计数和列名,这很有意义。 我不确定我想做的事仅适用于Mysql,我可以轻松地在PHP中做到这一点,但是我想知道是否也可以通过单个查询来做到这一点。

1 个答案:

答案 0 :(得分:0)

尝试以下查询。

select if(count(distinct(Name))=1,Name,null), if(count(distinct(Lastname))=1,Lastname,null), if(count(distinct(Age))=1,Age,null) from your_table;

相关问题