使用PHP从两个mysql表中选择数据

时间:2014-05-19 12:54:07

标签: php mysql sql

我有这个SQL查询:

SELECT 
  *,
  COUNT(*) as count
from tickets
where
  status = :status 
  and DATE(closed_timestamp) = '".date("Y-m-d")."' 
group by assigned_to 
order by count(*) DESC
LIMIT 3

但我想从closed_timestamp表中删除tickets列,并根据datetime表格中的ticket_updates列运行查询

ticketnumber表中的

tickets等于ticketnumber表中的ticket_updates(多行)

因此它应该在没有closed_timestamp列的情况下运行上述查询,并将其基于datetime表中的最新ticket_updates

示例

在故障单表格中有两行ticketnumber = 12345678

ticket_updates表中有3行..两行有ticketnumber = 1234,另一行有ticketnumber = 5678

我想显示票证中的所有行status = 'Completed'和上次更新(ticket_updates表)等于当前日期(2014-05-19)

2 个答案:

答案 0 :(得分:0)

使用join查询,如下所示,

SELECT 
  t.*,
  COUNT(t.*) as count
from tickets as t
LEFT JOIN ticket_updates as tu
ON tu.ticketnumber = t.ticketnumber
where
  t.status = :status 
group by t.assigned_to 
order by count(t.*) DESC
LIMIT 3

答案 1 :(得分:0)

试试这个:

SELECT *
FROM tickets t
JOIN (
  SELECT ticketnumber
  FROM ticket_updates
  WHERE DATE(datetime) = CURDATE()
) u
ON t.ticketnumber = u.ticketnumber
WHERE status = 'Completed'