[英]How to get the value from column 4 in a table where column 3 matches a value and column 4 matches a value ?
[英]Return Value in Column B Table 2, where column A Table 1, matches Column A Table 2
我正在尝试做的事情: 类别 (项目)与id (市场)匹配的地方echo 类别 (市场) 。
表1样本( 项目表)
表2样本( 市场表)
PHP代码样本
$num_rec_per_page=5;
if (isset($_GET["page"])) { $page = $_GET["page"]; } else { $page=1; };
$start_from = ($page-1) * $num_rec_per_page;
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$category= GET('category');
if ($category !== null) {
$sql = "SELECT * FROM projects WHERE category='$category' LIMIT $start_from, $num_rec_per_page";
} else {
$sql = "SELECT * FROM projects LIMIT $start_from, $num_rec_per_page";
}
$sql_query = mysql_query($sql);
$post = $sql_query;
$sql1 = "SELECT * FROM markets";
$sql_query1 = mysql_query($sql1);
$marketsinfo = mysql_fetch_array($sql_query1);
在下面的代码中,我尝试在主while循环中放置一个while循环,因为我们必须找出其所属的类别,然后为每篇博客文章进行显示。
它只对第一个结果起作用,然后我在网上进行了一些研究,发现这样做是非常糟糕的设计。
我目前在哪里显示结果(请参见连字符之间的代码):
<!-- Blog - Start -->
<?php while ($post = mysql_fetch_array($sql_query)) {?>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 blog blog_altered blog_left">
<div class="row">
<!-- Blog Image - Start -->
<div class=" col-lg-6 col-md-6 col-sm-10 col-xs-12 pic inviewport animated delay1" data-effect="fadeIn">
<img alt="blog-image" class="img-responsive" src="<?php echo $post['imageoutside'] ?>">
</div>
<!-- Blog Image - End -->
<!-- Blog Info - Start -->
<div class="col-lg-6 col-md-6 col-sm-12 col-xs-12 inviewport animated delay1" data-effect="fadeIn">
<div class="info">
----------------------------------------------------------------------
<span class="date">
<?php
if($post['category'] === $marketsinfo['id']){
echo $marketsinfo['category'];
}
?>
</span>
----------------------------------------------------------------------
<h4 class="title"><a href="projects/readmore.php?job=<?php echo $post['job'] ?>"><?php echo $post['title'] ?></a></h4>
<p><?php echo $post['summary'] ?></p>
<a class="btn btn-primary text-on-primary" href="projects/readmore.php?job=<?php echo $post['job'] ?>">Read More</a>
</div>
</div>
<!-- Blog Info - End -->
</div>
</div>
<?php } ?>
<!-- Blog - End -->
希望我已经足够彻底,不要感到困惑。 新手如何才能做到这一点? 我会告诉你的!
如果使用联接,则可以在一个查询中获得类别文本,并避免PHP中的所有循环。
向左联接将返回项目中的所有记录,并且仅返回与市场匹配的那些记录。 因此,如果市场中不存在项目类别,则将返回NULL值。
如果使用INNER JOIN,则仅返回两个表中具有相应值的记录。
经验法则:在需要时一次性从数据库中获取所需的数据。 格式为PHP,SQL为Datagrab。 不要得到比您需要的多的东西,也不要少得到的。
SELECT P.Job, M.ID as Markets_ID, M.Category, P.Title
FROM projects P
LEFT JOIN Markets M
on P.Category =M.ID
WHERE P.category='$category'
LIMIT $start_from, $num_rec_per_page"
注意:您需要在where子句中的类别上放置一个表别名。 我假设您传递了ID,因此使用了P.Category。
是否要按类别将表项目与表市场一起加入? 也许你可以做到这一点
SELECT p.id as id
, m.category as category
from projects as p
left
join markets as m
on p.category = m.id
WHERE m.category='$category'
LIMIT $start_from
, $num_rec_per_page
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.