我有一个mysql表jobs
。
这是jobs
的基本结构。
id
booked_user_id
assigned_user_id
然后我还有另一张表meta
。
Meta有结构:
id
user_id
first_name
last_name
这是我的PHP代码
$sQuery = "
SELECT SQL_CALC_FOUND_ROWS job_id, job_name, priority_id, meta.first_name, date_booked
FROM jobs
LEFT JOIN (meta) on (meta.user_id = jobs.booked_user_id)
LEFT JOIN (jobs_priorities) on (jobs_priorities.id = jobs.priority_id)
$sWhere
$sOrder
$sLimit
";
$rResult = mysql_query($sQuery);
while ( $aRow = mysql_fetch_assoc( $rResult ) )
{
$sOutput .= '"'.addslashes($aRow['job_id']).'",';
}
如何加入这些表格,以便booked_user_id
和assigned_user_id
都可以访问meta.first_name
?
当我尝试
时$sOutput .= '"'.addslashes($aRow['first_name']).'",
没有任何反应
感谢您的建议
添
答案 0 :(得分:2)
您可以加入两次:
SELECT j.id, b.first_name, a.first_name
FROM jobs j
JOIN meta b ON j.booked_user_id = b.user_id
JOIN meta a ON j.assigned_user_id = a.user_id
答案 1 :(得分:1)
Nathan做了修复,但会将它应用到您当前的SQL中,以便您可以更好地理解它
让我们将您的查询转换为:
SELECT SQL_CALC_FOUND_ROWS job_id, job_name, priority_id, date_booked
FROM jobs j
LEFT JOIN meta b ON b.user_id = j.booked_user_id
LEFT JOIN meta a ON a.user_id = j.assigned_user_id
LEFT JOIN jobs_priorities jp ON jp.id = j.priority_id
$sWhere
$sOrder
$sLimit
我所做的是使用方法的别名并加入两次meta(就像nathan所做的那样),我暂时删除了first_name字段,
然后让我们在SELECT上添加一些东西,这样你就可以显示first_name
SELECT SQL_CALC_FOUND_ROWS job_id, job_name, priority_id, date_booked, b.first_name as booked_first_name, a.first_name as assigned_first_name
FROM jobs j
LEFT JOIN meta b ON b.user_id = j.booked_user_id
LEFT JOIN meta a ON a.user_id = j.assigned_user_id
LEFT JOIN jobs_priorities jp ON jp.id = j.priority_id
$sWhere
$sOrder
$sLimit
现在,我们添加了columns_first_name和assigned_first_name列,现在你可以在你的php代码上调用它:
$ aRow ['booked_first_name']或$ aRow ['assigned_first_name']