1

我在 MySQL 中有三个表,它们连接在一起以显示用户拥有的资格。我想创建一个表,其中标题显示类型的完整列表,然后左侧列有用户名,然后列在类型标题下显示到期日期,如下所示:

Type
========
Type ID (PK, Int)
Type (VarChar)

User
========
User_ID (PK, Int)
Name (VarChar)

Qualification
========
Quali_ID (PK, Int)
User_ID (Int)
Type_ID (Int)
DateExpire (Date)
Status (VarChar)

我想像这样创建一个输出:

Users  Type1   Type2   Type3   Type4   .......
User1  Qual    Qual            Qual    .......
User2          Qual    Qual            .......
User3                  Qual            .......
User4  Qual    Qual    Qual    Qual    .......

并非所有用户都具有所有资格,并且受制于资格状态等于“完整”并且到期日期不是从今天开始的过去日期。

我在下面的互联网上搜索高低后创建了一些 SQL,但我无法让它包含不存在的类型。

我计划从 PHP 中的 MySQL 查询中获取结果并分解每一行以使其填充一个表。如果有人可以帮助我完成 SQL 以使其显示缺少的类型列或提出更好的方法,我将不胜感激。

我的 SQL:

SELECT 'User_ID', 'Name', GROUP_CONCAT(Types.Title ORDER BY QualiList.Type_ID) AS QualType
FROM TYPES
INNER JOIN (SELECT DISTINCT Type_ID FROM Qualification) QualiList
ON (QualiList.Type_ID = Types.Type_ID)

UNION ALL

SELECT User.User_ID, User.Name AS Name, GROUP_CONCAT(IFNULL(Qualification.DateExpire,'NA') ORDER BY QualiList.Type_ID) AS QualType
FROM TYPES
INNER JOIN (SELECT DISTINCT Type_ID FROM Qualification) QualiList
ON (QualiList.Type_ID = Types.Type_ID)
LEFT JOIN Qualification ON (Qualification.Type_ID = QualiList.Type_ID)
INNER JOIN User ON (User.User_ID = Qualification.User_ID)
GROUP BY Name
4

1 回答 1

0

检查答案

SELECT USER,
 if(sum(user_id*(1-abs(sign(type_id-1))))>0,DateExpire,'NA') AS TypeADate,
 if(sum(user_id*(1-abs(sign(type_id-1))))>0,Status,'NA') AS TypeAStatus,
 if(sum(user_id*(1-abs(sign(type_id-2))))>0,DateExpire,'NA') AS TypeBDate,
 if(sum(user_id*(1-abs(sign(type_id-2))))>0,Status,'NA') AS TypeBStatus,
 if(sum(user_id*(1-abs(sign(type_id-3))))>0,DateExpire,'NA') AS TypeCDate,
 if(sum(user_id*(1-abs(sign(type_id-3))))>0,Status,'NA') AS TypeCStatus

 FROM (
   SELECT U.USER, T.Type, Q.Type_ID, Q.User_ID,Q.DateExpire,Q.Status FROM Qualification Q
 LEFT OUTER JOIN TYPE T
   ON Q.Type_id = T.ID
 LEFT OUTER JOIN USER U
   ON Q.User_id = U.ID
 GROUP BY T.ID, U.ID
 ) xxx GROUP BY USER

检查http://www.sqlfiddle.com/#!2/c1233/16上的答案

于 2012-11-20T23:52:31.090 回答