交叉引用多个表

时间:2015-11-05 06:11:13

标签: mysql join database-table

我想要做的是从多个表中获取数据,假设我在查询中有以下结果: enter image description here

列ticket_item_type中的数字表示某个表。例如,2表示tbl_company,3表示tbl_lease。然后详细信息表示该表中某条记录的ID。

假设我想使用ticket_item_type和详细信息获取这些记录的标题。是否有可能将其嵌入到结果中?或者我应该为每个查询单独进行查询。

我知道JOIN,但我只是单桌吗?

这是我上面图片的MYSQL查询:

SELECT *
FROM
  (SELECT *
   FROM ticket_items
   WHERE hs_customer = 1
     AND ticket IN
       (SELECT id
        FROM tickets
        WHERE hs_customer='1'
          AND ticket_status = 'dispatch_reviewed')
     AND ticket IN
       (SELECT ticket
        FROM ticket_items
        WHERE ticket_item_type = 5
          AND details = '159')) AS TB1
WHERE ticket_item_type IN (3,
                           2,
                           8)

1 个答案:

答案 0 :(得分:0)

您可以尝试这样的事情:

SELECT 
    TB1.*,
    CASE
    WHEN TB1.ticket_item_type = 2 THEN t2.title
    WHEN TB1.ticket_item_type = 3 THEN t3.title
    WHEN TB1.ticket_item_type = 8 THEN t8.title
    ELSE 'NA'
    END as title
FROM
(
   SELECT *
   FROM ticket_items
   WHERE hs_customer = 1
     AND ticket IN (SELECT id FROM tickets WHERE hs_customer='1' AND ticket_status = 'dispatch_reviewed')
     AND ticket IN (SELECT ticket FROM ticket_items WHERE ticket_item_type = 5 AND details = '159')
) AS TB1
LEFT JOIN tbl_company t2 ON TB1.details = t2.id
LEFT JOIN tbl_lease t3 ON TB1.details = t3.id
LEFT JOIN tbl_next t8 ON TB1.details = t8.id
WHERE ticket_item_type IN (3, 2, 8)

但是,这不是我喜欢的设计。如果不查看数据库的详细信息,编写查询以覆盖多种类型的ticket_item_type将会很困难。我希望这个查询对你有用。