我有这个问题:
$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
列。我怎样才能做到这一点?它甚至可能吗?
答案 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