是否可以在运行另一个查询时生成查询结果?

时间:2013-02-24 23:13:30

标签: php mysql

我有这个问题:

$aircraft_query = "SELECT COUNT(aircraft) as total, aircraft FROM db_pireps WHERE pilotid = $pilotid GROUP BY aircraft ORDER BY total DESC LIMIT 6";
$planes = DB::get_results($aircraft_query);

使用foreach语句,我可以在表格中生成行,以显示pilotid飞行的飞机。但是,我现在希望RESULT链接到另一个表并从fullname列中提取数据,例如飞机类型。

我有:<?php echo $aircraft->fullname; ?>,但该数据位于不同的表格中。因此,如果aircraft为30,则会访问db_aircrafts表中的第30条记录并取fullname列。我怎样才能做到这一点?它甚至可能吗?

2 个答案:

答案 0 :(得分:1)

您应该使用SQL连接。

SELECT COUNT(A.aircraft) as total, A.aircraft, B.fullname
 FROM db_pireps A
 LEFT JOIN pilot_data_table B ON A.pilotid = B.id
 WHERE A.pilotid = $pilotid
 GROUP BY A.aircraft ORDER BY total DESC LIMIT 6

答案 1 :(得分:1)

您需要的是一个表JOIN(另见JOIN in MySQL manual):

SELECT 
    COUNT(a.aircraft) as total
    , a.aircraft
    , b.fullname AS aircraft_name
FROM db_pireps AS a
JOIN db_aircraft AS b
    ON a.aircraft = b.id
WHERE pilotid = {$pilotid}
GROUP BY aircraft 
ORDER BY total DESC 
LIMIT 6