我目前正在尝试创建一个SQL语句,允许我从两个表中检索信息,第三个表从每个表和类型中都有post_id
。这样我就可以知道post_id
来自哪个表格。
ALL_POSTS:
id PRIMARY KEY,
post_id (FOREIGN KEY)
type
电影:
post_id
type
title
MUSIC:
post_id
type
title
band
这是我使用的SQL语句:
SELECT a.*, b.*, c.* FROM ALL_POSTS as a, MOVIES as b, MUSIC as c WHERE (a.post_id = b.id AND a.type = b.type) OR (a.post_id = c.id AND a.type = c.type)
问题在于它检索了很多结果,并且所有结果都来自MUSIC表,并且大部分都是重复的。
由于
答案 0 :(得分:1)
您应该在两个表上使用 LEFT JOIN 。这样,它将返回 ALL_POSTS 表中的所有行以及 MOVIES 和 MUSIC 表中的相应详细信息。
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<!-- Latest compiled and minified CSS -->
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<!-- Latest compiled and minified JavaScript -->
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" integrity="sha384-Tc5IQib027qvyjSMfHjOMaLkfuWVxZxUPnCJA7l2mCWNIpG9mGCD8wGNIcPD7Txa" crossorigin="anonymous"></script>
<div class="panel panel-default">
<div class="panel-heading">
<i class="fa fa-calendar fa-fw"></i> System Years
<div class="pull-right">
<button type="button" class="btn btn-info btn-xs btn-add-year " data-toggle="tooltip" title="Add year"><i class="fa fa-plus"></i></button>
</div>
</div>
<!-- /.panel-heading -->
<div class="panel-body">
<div class="table-responsive">
<table class="table table-bordered table-hover table-striped">
<tbody>
<tr>
<td>
<strong>2014</strong>
<div class="btn-group">
<button type="button" class="btn btn-success btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Menu 1 <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="javascript:;">All</a></li>
<li><a href="javascript:;">Other</a></li>
</ul>
</div>
</td>
</tr>
<tr>
<td>
<strong>2015</strong>
<div class="btn-group">
<button type="button" class="btn btn-success btn-xs dropdown-toggle" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Menu 2 <span class="caret"></span>
</button>
<ul class="dropdown-menu">
<li><a href="javascript:;">All</a></li>
<li><a href="javascript:;">Other</a></li>
</ul>
</div>
</td>
</tr>
</tbody>
</table>
</div>
<!-- /.table-responsive -->
</div>
<!-- /.panel-body -->
</div>
答案 1 :(得分:0)
目前,您正在从三个表中生成笛卡尔积。请改用JOIN
:
SELECT A.*, B.*, C.* FROM ALL_POSTS AS A
LEFT JOIN MOVIES AS B ON A.post_id = B.ID AND A.type = B.type
LEFT JOIN MUSIC AS c ON A.post_id = C.ID AND A.type = C.type