SQL查询以获得所需的结果

时间:2014-10-08 07:32:45

标签: php mysql

我有2张桌子。我想要输出的mysql查询,如屏幕截图所示:

enter image description here

有没有解决方案?

2 个答案:

答案 0 :(得分:0)

试试这个:

SELECT Table_1.Firstname, Table_2.Lastname, Table_2.RF1 AS 'RaterFirst', Table_2.RL1 AS 'RaterLast' FROM Table_1, Table_2 WHERE (Table_1.ID = Table_2.ID)
UNION
SELECT Table_1.Firstname, Table_2.Lastname, Table_2.RF2 AS 'RaterFirst', Table_2.RL2 AS 'RaterLast' FROM Table_1, Table_2 WHERE (Table_1.ID = Table_2.ID)
UNION
SELECT Table_1.Firstname, Table_2.Lastname, Table_2.RF3 AS 'RaterFirst', Table_2.RL3 AS 'RaterLast' FROM Table_1, Table_2 WHERE (Table_1.ID = Table_2.ID)

但我想告诉你,这不是设计数据库表Table_2的正确方法 您必须为每个ID保留多个记录行。 查看First Normal Form

答案 1 :(得分:0)

您可以使用:

Select Firstname, Lastname, Table_2.RF1 AS Raterfirst, Table_2.RL1 AS Raterlast
From Table_1
Inner Join Table_2
ON Table_1.ID = Table_2.ID
WHERE Raterfirst <> '' OR Raterlast <> ''

UNION

Select Firstname, Lastname, Table_2.RF2 AS Raterfirst, Table_2.RL2 AS Raterlast
From Table_1
Inner Join Table_2
ON Table_1.ID = Table_2.ID
WHERE Raterfirst <> '' OR Raterlast <> ''

UNION 

Select Firstname, Lastname, Table_2.RF3 AS Raterfirst, Table_2.RL3 AS Raterlast
From Table_1
Inner Join Table_2
ON Table_1.ID = Table_2.ID
WHERE Raterfirst <> '' OR Raterlast <> ''

您可以优化此SQL命令,例如只使用一个Where表达式。