我试图在MySql查询中插入两个不同表中的“标题”。如果我尝试下面的第一个查询,它的工作原理。一旦我添加第二个LEFT JOIN
,它仍会获得第一个“博客”标题,但不会获得第二个“专辑”标题。关于如何从两个表中获取两个标题的任何想法?请注意,我需要确保每个都有这两个条件:updates.ref_table = 'albums' AND updates.ref_id = albums.id
作品...
$query = "SELECT updates.*, albums.title FROM updates ";
$query .= "LEFT JOIN albums ON updates.ref_table = 'albums' AND updates.ref_id = albums.id ";
$query .= "WHERE user_id = ".$user_id." ORDER BY date DESC";
不要工作......
$query = "SELECT updates.*, albums.title, blog.title FROM updates ";
$query .= "LEFT JOIN blog ON updates.ref_table = 'blog' AND updates.ref_id = blog.id ";
$query .= "LEFT JOIN albums ON updates.ref_table = 'albums' AND updates.ref_id = albums.id ";
$query .= "WHERE user_id = ".$user_id." ORDER BY date DESC";
答案 0 :(得分:0)
如果结果中有多个列具有相同的名称,您将只获得一个结果,因此重命名具有相同名称的列,您将获得所有列,并且它们将具有有意义的名称,因此您知道哪一个是哪个。
$query = "SELECT updates.*, albums.title as albumtitle, blog.title as blogtitle FROM updates ";
$query .= "LEFT JOIN blog ON updates.ref_table = 'blog' AND updates.ref_id = blog.id ";
$query .= "LEFT JOIN albums ON updates.ref_table = 'albums' AND updates.ref_id = albums.id ";
$query .= "WHERE user_id = ".$user_id." ORDER BY date DESC";