我有一个 MySQL 数据库,我正在尝试创建一个 Web 界面来管理票证,现在我正在尝试像这样列出票证: [标题][创建工单的人的姓名][优先级][创建日期][负责此工单的人]
所以我有一个名为 tickets 的表,其中包含标题、创建票证的人的 ID、优先级和日期。
我有另一个名为用户的表,您可以在其中找到名字和姓氏以及一些其他信息及其 ID(您可以使用该 ID 链接两个表)
我有另一个名为 tickets_users 的表,您可以在其中找到负责门票的人员的 ID
我的问题是我不知道如何在一个请求中链接所有这些,如果只有一个人负责一张票会很简单但可以有多个人,我尝试了一些查询但我总是得到当有多于一个人负责票务时,票务标题等加倍。
提前致谢 编辑 表格示例:
tickets:
-id = 523 | title = help with internet explorer | priority = 3 | date = 2013-10-10 11:20:51
users:
-id = 25 | firstname = John | lastname = Light
-id = 35 | firstname = Dwight | lastname = Night
-id = 53 | firstname = Maria | lastname = Sun
tickets_users :
-ticketid = 523 | userid = 25 | type = 1
-ticketid = 523 | userid = 35 | type = 2
-ticketid = 523 | userid = 53 | type = 2
我希望能够请求显示:
[help with internet explorer][John Light][3][2013-10-10 11:20:51][Maria Sun - Dwight Night]
一行(每张票)和我数据库中的所有票
最佳答案
您可以使用 group_concat
聚合函数将链接人员的姓名分组到结果中的单个字段中。由于我没有您确切的表结构,所以我已经编造了字段和表的名称。
select
t.title,
group_concat(
case when tu.type = 1 then
concat(u.firstname, ' ', u.lastname)
end) as creator,
t.priority,
t.date,
group_concat(
case when tu.type = 2 then
concat(u.firstname, ' ', u.lastname)
end SEPARATOR ' - ') as users
from
tickets t
inner join tickets_users tu on tu.ticketid = t.id
inner join users u on u.id = tu.userid
group by
t.id;
如果一张票确实只有一个创建者(这是有道理的),那么我会给票一个 creatoruserid
来引用 John
。在这种情况下,John 不需要在联结表中,您实际上也不再需要 type
列。
关于php - 需要有关连接表的帮助,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17710871/