MySql查询来自多个表的数据

时间:2012-09-12 00:46:03

标签: mysql sql report reporting

我是SQL的新手,所以请善待。我可以通过查看数据库并将其导出到excel来获取所有信息。一旦进入excel,我必须创建forumlas以获得我想要的一切。如果可能的话,我想运行一个查询来查看它。我有谷歌,但我似乎无法找到对我有意义或指向正确方向的东西。

我认为通过我的搜索会有一些联接但又是SQL的新手我正抓住稻草。

给出以下样本表:

门票表:

ID    Queue  Owner  Subject            Status    TimeWorked    LastUpdated
001   1      22     need help          Open      20            2012-09-01
002   2      6      internet           Resolved  60            2012-09-03
003   1      24     email not working  Open      15            2012-09-04

用户表:

ID    Name
6     Nobody
22    Josh
24    Jon

CustomFieldValue表:

Id      ObjectId    CustomField    Content
01      001         1              Bob Inc
02      001         2              0
03      001         3              WaitingOnClient
04      001         4              Remote
05      002         1              ZYC Inc
06      002         2              15
07      002         3              WaitingOnClient
08      002         4              Remote
09      003         1              ACB Inc
10      003         2              0
11      003         3              TimeScheduled
12      003         4              OnSite

队列表:

ID    Name
1     Support
2     Tier2

我需要做的是查询以使结果看起来像下面的

ID  Client  Subject   Queue    Owner  Status    Type   BTime CustomStat      LastUpdate NT
001 Bob Inc need help support  Josh   open      Remote 20    WaitingOnClient 2012-09-01 0
001 ZYC Inc internet  Tier2    Nobody Resolved  Remote 60    WaitingOnClient 2012-09-01 15
001 ACB Inc email     support  Jon    open      onsite 15    TimeScheduled   2012-09-01 0

非常感谢任何帮助。

提前致谢

1 个答案:

答案 0 :(得分:2)

您需要使用内联 CASE语句GROUP_CONCAT,并且应按ID分组。试一试。

SELECT  a.ID,
        GROUP_CONCAT((CASE WHEN d.CustomeField = 1 THEN d.content ELSE NULL END)) `Client`,
        a.Subject,
        c.Name,
        b.Name Owner,
        a.`Status`,
        GROUP_CONCAT((CASE WHEN d.CustomeField = 4 THEN d.content ELSE NULL END)) `Type`,
        a.TimeWorked,
        GROUP_CONCAT((CASE WHEN d.CustomeField = 3 THEN d.content ELSE NULL END)) `CustomStat`,
        a.LastUpdated,
        GROUP_CONCAT((CASE WHEN d.CustomeField = 2 THEN d.content ELSE NULL END)) `NT`
FROM    tickets a
        INNER JOIN users b
            ON a.owner = b.id
        INNER JOIN queue c
            ON a.queue = c.id
        INNER JOIN  CustomFieldValue d
            ON a.ID = d.ObjectID
 GROUP BY a.ID

SQLFiddle Demo