交叉引用多个表
Cross Referencing Multiple Tables
我想做的是从多个 table 中获取数据,假设我的查询中有以下结果:
ticket_item_type栏中的数字代表某table。例如,2 代表 tbl_company,3 代表 tbl_lease。那么details代表的是那个table.
中某条记录的id
假设我想使用 ticket_item_type 和详细信息获取那些记录的标题。是否可以将其嵌入到结果中?或者我应该为每个单独查询。
我知道JOIN,但我是单人的吗table?
这是我对上图的 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)
您可以尝试这样的操作:
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 的查询。不过,我希望这个查询对你有用。
我想做的是从多个 table 中获取数据,假设我的查询中有以下结果:
ticket_item_type栏中的数字代表某table。例如,2 代表 tbl_company,3 代表 tbl_lease。那么details代表的是那个table.
中某条记录的id假设我想使用 ticket_item_type 和详细信息获取那些记录的标题。是否可以将其嵌入到结果中?或者我应该为每个单独查询。
我知道JOIN,但我是单人的吗table?
这是我对上图的 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)
您可以尝试这样的操作:
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 的查询。不过,我希望这个查询对你有用。