0

我正在尝试在 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";
4

1 回答 1

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";
于 2013-07-03T00:01:36.240 回答