SQL INNER JOIN返回的行数多于我需要的行数

时间:2013-07-08 18:50:37

标签: mysql sql

这是我的情况:

我有2张桌子,门票门票详情。我需要检索“票证”中的信息,并从每张票证的“ticket-details”中获取最后一个回复,然后在表格中显示em。我的问题是“ticket-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

---------------------------------- EDIT ------------ -----------------------------------

我的桌子:

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

门票详情( id_ticketDetail ,id_ticket,dateReply,回复)

3 个答案:

答案 0 :(得分: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 演示。

答案 1 :(得分: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)

答案 2 :(得分: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