我有这个问题:
SELECT p.status, s.name AS "Senior", j.name AS "Junior", sp.name AS "Sophomore", f.name AS "Freshman"
FROM matrix p
LEFT JOIN senior s ON p.id = s.id
LEFT JOIN junior j ON p.id = j.id
LEFT JOIN sophomore sp ON p.id = sp.id
LEFT JOIN freshman f ON p.id = f.id
ORDER BY f.name, sp.name, j.name, s.name DESC
返回此结果:
| Senior | Junior | Sohpomore | Freshman |
------------------------------------------
| Value | NULL | NULL | NULL |
| Value | NULL | NULL | NULL |
| Value | NULL | NULL | NULL |
| NULL | Value | NULL | NULL |
| NULL | Value | NULL | NULL |
| NULL | Value | NULL | NULL |
| NULL | NULL | Value | NULL |
| NULL | NULL | Value | NULL |
| NULL | NULL | Value | NULL |
| NULL | NULL | NULL | Value |
| NULL | NULL | NULL | Value |
| NULL | NULL | NULL | Value |
我的问题是,是否可以将第二列,第三列和第四列的值向上移动以使它们全部对齐(并且所有空值都显示在底部)?在此先感谢您的帮助。
顺便说一句,我正在使用PHP检索这些值,如果有帮助的话。
更新:状态不是唯一的。它只能是2个值,我没有向用户显示。另外,为了让我的问题更清楚一点,这是我想要完成的结果:
| Senior | Junior | Sohpomore | Freshman |
------------------------------------------
| Value | Value | Value | Value |
| Value | Value | Value | Value |
| Value | Value | Value | Value |
| NULL | Value | NULL | Value |
| NULL | Null | NULL | Value |
| NULL | Null | NULL | NULL |
更新2 以下是所有表格的结构:
Matrix: ID, Status, Student Name, Major, Class Standing
Senior: ID, Name
Junior: ID, Name
Sophomore: ID, Name
Freshman: ID, Name
答案 0 :(得分:0)
我认为你可以用聚合来做到这一点:
SELECT p.status, max(s.name) AS "Senior", max(j.name) AS "Junior",
max(sp.name) AS "Sophomore", max(f.name) AS "Freshman"
FROM matrix p
LEFT JOIN senior s ON p.id = s.id
LEFT JOIN junior j ON p.id = j.id
LEFT JOIN sophomore sp ON p.id = sp.id
LEFT JOIN freshman f ON p.id = f.id
GROUP BY p.status
ORDER BY f.name, sp.name, j.name, s.name DESC
答案 1 :(得分:0)
我没有足够的声誉发表评论,所以我会问这里;你试图让每一行代表什么?有一个'status'字段 - 这对每个类表都是唯一的吗?即如果有“A”状态,是否只有一名新生,大二,大三和大四与该状态相对应?
在我(或任何人)提供任何解决方案之前,我需要更多地了解您正在使用的数据以及您要完成的任务。
编辑:这是我认为最有可能是你最好的选择(我现在无法测试,所以如果我错过了语法错误,请道歉)。它将为您提供一个长而窄的学生列表,其中包含“类”字段,您可以使用它来区分CSS:
SELECT
p.status,
"senior" AS class,
s.name
FROM
matrix AS p
JOIN senior AS s
ON p.id = s.id
UNION
SELECT
p.status,
"junior" AS class,
j.name
FROM
matrix AS p
JOIN junior AS j
ON p.id = j.id
UNION
SELECT
p.status,
"sophomore" AS class,
sp.name
FROM
matrix AS p
JOIN sophomore AS sp
ON p.id = sp.id
UNION
SELECT
p.status,
"freshman" AS class,
f.name
FROM
matrix AS p
JOIN freshman AS f
ON p.id = f.id;