gpt4 book ai didi

php - MySQL跨表查询3张表,空值显示格子

转载 作者:行者123 更新时间:2023-11-30 23:25:41 25 4
gpt4 key购买 nike

我在 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 以使其显示缺少的 Type 列或提出更好的方法,我将不胜感激。

我的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

最佳答案

检查答案

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 上的答案

关于php - MySQL跨表查询3张表,空值显示格子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13483789/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com