MySQL加入特定结果

标签 mysql join

我正在尝试构建一个查询以从表单生成器中提取数据,我只能在另一个字段值等于特定值的情况下加入一个字段值。我的查询没有返回任何行。

users
------------------
|id | name       |
------------------
|40 | John       |
|45 | Michael    |
|47 | Bob        |
------------------    

data_table
----------------------------------------------------
|id  | submission | field_type | field_value       |
----------------------------------------------------
|1   | 12345      | user       | 40                |
|2   | 12345      | score      | 5                 |
|3   | 12345      | completed  | 1                 |
|4   | 23456      | user       | 45                |
|5   | 23456      | score      | 3                 |
|6   | 23456      | completed  | 0                 |
|7   | 45678      | user       | 47                |
|8   | 45678      | score      | 2                 |
|9   | 45678      | completed  | 1                 |
----------------------------------------------------

Desired result

---------------
|Name | Score |
---------------
|John | 5     |
|Bob  | 2     |
---------------

Select 
    u.name,
    dt2.field_value as score
from
    users u
left join
    data_table dt on u.id=dt.field_value and dt.field_type='user'
left join
    data_table dt2 on dt.submission=dt2.submission and dt2.field_type='score'
where
    (dt.field_type='completed' and dt.field_value=1)

http://sqlfiddle.com/#!2/d6e72f/3

最佳答案

你可以做类似的事情(如果你真的不能改变你的数据结构,这看起来......很奇怪)。

你将在 data_table 上有一个子查询,在该表上有两个自连接(因为你需要 3 个不同的行和条件)

select u.name, s.score
from users u
join (
      select dt.field_value as user_id, dt1.field_value as score
      from data_table dt
      join data_table dt1 on dt1.submission = dt.submission
      join data_table dt2 on dt2.submission = dt1.submission
      where dt.field_type='user' and 
            dt1.field_type = 'score' and 
            dt2.field_type='completed' and 
            dt2.field_value = 1
      ) s
    on s.user_id = u.id

参见 SqlFiddle

关于MySQL加入特定结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27910933/

相关文章:

php - 如何连接mysql中不同表的2个值

php - 将 PHP 变量传递给模态并在 MySQL 查询中使用它

嵌入自动终止的 Mysql 查询

mysql - JOIN 两个查询结果(具有 WHERE 和 IN 子句 + 子查询)

Mysql SELECT 不工作

r - 连接data.table时如何找到最近的最大值

php - 使用 Zend (1.12.17) 和 Ajax 的动态下拉列表

mysql - 如果值存在于其他表中,则返回该表中的另一个值

PHP MySQL : update table with value of an array combine

mysql - 在 mySQL 查询中使用正确的连接