1

这是我的情况:

我有 2 张桌子,门票门票详细信息。我需要检索“tickets”中的信息,以及每张门票的“tickets-details”的最后回复,然后在表格中显示它们。我的问题是“票务详情”每次回复都会返回一行,而每张票我得到的不止一行。如何在单个查询中实现这一点?

我尝试添加DISTINCT到我的SELECT但没有。

我尝试使用GROUP BY id_ticket但也没有工作,因为我没有从票务详细信息中得到最后的回复

这是我的查询:

SELECT DISTINCT ti.id_ticket,ti.title,tiD.Reply,ti.status 
FROM tickets ti 
INNER JOIN ticket-details tiD ON ti.id_ticket = tiD.id_ticket 
WHERE user = '$id_user' ORDER BY status desc

- - - - - - - - - - - - - - - - - 编辑 - - - - - - - - --------------------------------

我的桌子:

门票(id_ticket,用户,日期,标题,状态)

工单详细信息(id_ticketDetail,id_ticket,dateReply,reply)

4

3 回答 3

2

假设最大值代表您可以尝试id_ticketDetail的最新记录ticket-details

SELECT ti.id_ticket,
       ti.title,
       tiD.Reply,
       ti.status 
  FROM tickets ti JOIN 
(
    SELECT id_ticket, reply
      FROM `ticket-details` d JOIN 
    ( 
        SELECT MAX(id_ticketDetail) max_id
          FROM `ticket-details`
         GROUP BY id_ticket
    ) q ON d.id_ticketDetail = q.max_id
) tiD ON ti.id_ticket = tiD.id_ticket 
 WHERE ti.user = '$id_user' 
 ORDER BY ti.status DESC

或最大版本dateReply

SELECT ti.id_ticket,
       ti.title,
       tiD.Reply,
       ti.status 
  FROM tickets ti JOIN 
(
    SELECT d.id_ticket, d.reply
      FROM `ticket-details` d JOIN 
    ( 
        SELECT id_ticket, MAX(dateReply) max_dateReply
          FROM `ticket-details`
         GROUP BY id_ticket
    ) q ON d.id_ticket = q.id_ticket
       AND d.dateReply = q.max_dateReply
) tiD ON ti.id_ticket = tiD.id_ticket 
 WHERE ti.user = '$id_user' 
 ORDER BY ti.status DESC

这是两个查询的SQLFiddle演示。

于 2013-07-08T18:59:45.947 回答
1

我不知道您的数据库模型,但如果 ID 是自动递增的,您可以使用以下条件扩展您的脚本:

SELECT ti.id_ticket,ti.title,tiD.Reply,ti.status 
FROM tickets ti 
 INNER JOIN ticket-details tiD ON ti.id_ticket = tiD.id_ticket 
WHERE user = '$id_user' 
 and tiD.id_ticket in (select max(a.id) from ticket-details a group by a.id_ticket)
ORDER BY status desc

或者,如果您有某种日期属性,请将新条件更改为您的日期属性(在我的示例中为 ticked_date )

and tiD.ticked_date in (select max(a.ticked_date) from ticket-details a group by a.id_ticket)
于 2013-07-08T19:01:01.333 回答
0

如果您需要获取一堆带有票证详细信息的票证,则添加子查询会起作用(尽管效率有点低):

SELECT DISTINCT 
    ti.id_ticket,ti.title,tiD.Reply,ti.status 
FROM tickets ti INNER JOIN ticket-details tiD 
    ON ti.id_ticket = tiD.id_ticket 
WHERE user = '$id_user' AND 
    tiD = (select id from ticket-details where ticket-details.id_ticket = ti.id_ticket ORDER BY ticket-details.date_field DESC LIMIT 1) ORDER BY status desc

如果您一次只需要为一张票执行此操作,则只需按票详细信息中的日期字段排序并在其中设置限制即可:

SELECT DISTINCT 
    ti.id_ticket,ti.title,tiD.Reply,ti.status 
FROM tickets ti INNER JOIN ticket-details tiD 
    ON ti.id_ticket = tiD.id_ticket 
WHERE user = '$id_user' ORDER BY tiD.date_field, status DESC LIMIT 1
于 2013-07-08T19:00:47.180 回答