mysql合并两个表产生以下输出

标签 mysql mysql-workbench

你好,我之前也问过同样的问题,但我想要另一种方式。我们可以使用 locate 和 max 函数来解决这个问题。但是我的老师让我这样做

  1. 当 '0' 然后 '1' 否则 '0' 时,我的代码是这样的

         select u.id, u.name, 
         case f.finger when '0' then '1' else '0' end as '0',
         case f.finger when '1' then '1' else '0' end as '1',
         case f.finger when '2' then '1' else '0' end as '2',
         case f.finger when '3' then '1' else '0' end as '3',
         case f.finger when '4' then '1' else '0' end as '4',
         case f.finger when '5' then '1' else '0' end as '5'
    
         from users u left join user_fingerprints f
         on u.id= f.user_id
    

    上面的代码将生成 8 行。

  2. 然后我需要合并这些行,以便具有相同 id 的行合并生成这个

  3. 然后根据该结果使用案例功能。当值为 1 时,则为 y。当值为零时,则为 n。

有人可以在不使用 max 函数的情况下给我答案吗?谢谢
表格和结果 enter image description here

最佳答案

您也可以使用 SUM() 和另一个 CASE EXPRESSION 来完成:

SELECT t.id,t.name,
       CASE WHEN t.`0` > 0 THEN 'Y' ELSE 'N' as `0`
       CASE WHEN t.`1` > 0 THEN 'Y' ELSE 'N' as `1`
       ....
FROM (
    SELECT u.id,u.name, 
           SUM(CASE WHEN f.finger = '0' then '1' else '0' end) as `0`,
           SUM(CASE WHEN f.finger = '1' then '1' else '0' end) as `1`,
           ....
    from users u left join user_fingerprints f
     on u.id= f.user_id
    GROUP BY u.id,u.name) t

关于mysql合并两个表产生以下输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38845116/

相关文章:

mysql - 使用子查询和分组依据计算每个国家/地区每日 DAU 平均值

MySQL JDBC 驱动程序连接字符串?

mysql - 是否可以在 MYSQL WORKBENCH 的列中强制输入一定数量的数字?

mysql - 如何在 SQL 中创建前 5 列和后 5 列?

mysql - InnoDb 有时工作但其他时间不工作

mysql - 比较两个 MySQL 表并选择第二个表中的不同条目

mysql - 尝试链接 phoenix 和 MySQl compile.gettext 错误

mysql - 为什么 MySql SUBDATE(now(3), 2) 函数在毫秒内添加额外的三位数?

MySQL 工作台 : including triggers in creation script

php - 使用 mysqli 和 php 实例化构造函数类