查询以下表的pivtol表-MySQL

时间:2019-01-18 20:31:23

标签: php mysql

我有3个具有以下架构的表:

需求类别

+----+--------+----------+
| id |  name  | category |
+----+--------+----------+
| 1  | Height | D        |
|  2 | Age    | D        |
|  3 | Time   | E        |
+----+--------+----------+

项目要求

+----+----------------+-------------------+------------+
| id | requirement_id | requirement_value | project_id |
+----+----------------+-------------------+------------+
| 1  |              1 | Tall              |          1 |
|  2 |              1 | Medium            |          1 |
|  3 |              1 | Short             |          1 |
|  4 |              2 | Young             |          1 |
|  5 |              2 | Middle            |          1 |
|  6 |              2 | Senior            |          1 |
|  7 |              3 | Day               |          1 |
|  8 |              3 | Night             |          1 |
+----+----------------+-------------------+------------+

ProjectTestRequirements

+----+-------------+----------+------------------------+
| id | project_id  | test_id  | project_requirement_id |
+----+-------------+----------+------------------------+
| 1  |           1 |        1 |                      1 |
|  2 |           1 |        1 |                      5 |
|  3 |           1 |        1 |                      8 |
+----+-------------+----------+------------------------+

ProjectTests

+----+-------------+----------+
| id | project_id  | test_id  |
+----+-------------+----------+
| 1  |           1 |        1 |
+----+-------------+----------+

我想要这样的输出:

+---------+--------+--------+-------+
| test_id | Height |  Age   | Time  |
+---------+--------+--------+-------+
|      1  | Tall   | Middle | Night |
+---------+--------+--------+-------+

我正在尝试使用laravel进行此操作,但我需要知道如何编写查询以获取共享的输出。

我尝试了以下

  SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'max(case when rc.name = ''',
      name,
      ''' then pr.requirement_value end) AS ',
      replace(name, ' ', '')
    )
  ) INTO @sql
from requirement_categories;

SET @sql = CONCAT('
SELECT
    ptr.test_id, ', @sql, ' 
from 
    project_test_requirements ptr
    project_requirements pr,
    requirement_categories rc,
    project_test pt
where
    ptr.test_id=pt.test_id
    and
    ptr.requirement_id = pr.id
    and
    rc.id = pr.requirement_id
group by 
    ptr.test_id
');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

它抛出此错误:

16:11:54    PREPARE stmt FROM @sql  Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'Group,max(case when rc.name = 'height' then pr.requirement_value end) AS height ' at line 2    0.000 sec

0 个答案:

没有答案