来自不同表的查询如何加入Suggest PLease(PHP)(SQL)

时间:2012-03-22 13:08:32

标签: php sql

我需要有关JOIN表的帮助才能获得类别名称&来自其他表的作者姓名。

对于文章网站我有三个表

  • 制品
  • 类别
  • 用户

文章表格结构:

id
title
slug
content
category
author
date

我保存了类别ID&每篇文章的文章表中的用户ID

在显示某个类别的文章时,我使用此方法: (只是一些草案不是完整的代码)

localhost/testsite/category.php?cat=category-slug

$catslug = ($_GET["cat"]);

//GET CAT ID from category table from slug

$qry = "SELECT * from category WHERE slug='$catslug';
$res = mysql_query($qry) or die("Error in Query");
$ans = mysql_fetch_array($res);
$cid = $ans['id'];
$catname = $ans['title'];

<h2><?php echo $catname; ?></h2>

//after getting cat-id query to get article of that ID

$aqry = select * from article where category=$cid ORDER BY date";
$ares = mysql_query($aqry) or die("Error in Query");
$aans = mysql_fetch_array($ares))
$aid = $aans['author'];

//then another query to get author name from users
select username from users where id=$aid

我正在学习PHP&amp;不太熟悉JOIN声明&amp;结合查询 需要帮助/建议我可以通过JOIN表而不是不同的查询实现相同的操作来从表中获取catname和author name。

由于

5 个答案:

答案 0 :(得分:0)

假设类别ID是文章表中的外键

尝试此查询

select username from users
where id in (
select author from category cat
inner join article art 
on cat.category_id =art.category_id
where cat.slug= $cat
order by art.date desc )

答案 1 :(得分:0)

这应该做你想要的事情

SELECT distinct c.title, U.Username
from category C join article A on A.category=C.id
join users U on U.id=A.author
WHERE C.slug= :catslug

答案 2 :(得分:0)

$q = "SELECT article.*
        FROM article
             LEFT JOIN category
             ON article.category = category.ID
             LEFT JOIN users
             ON article.author = users.ID
       WHERE article.slug = :slug";

:slug是您要插入的位置(如果您正在使用PDO,则绑定)$_GET['slug']

答案 3 :(得分:0)

首先,您应该编写一个存储过程...但是这里是如何通过categoryID获取包含类别名称和用户名的文章。

给出以下表格结构:

article
---------
articleID <- primary key
title
slug
content
categoryID <- foreign key
userID <- foreign key
createdDT

category
--------
categoryID <- primary key
categoryName

user
--------
userID <- primary key
userName

以下是使用连接编写查询的方法:

SELECT a.title, a.slug, a.content, a.createdDT, c.categoryName, u.userName

FROM dbo.article a

JOIN dbo.category c on a.categoryID = c.categoryID
JOIN dbo.user u on a.userID = u.userID

WHERE a.categoryID = @categoryID

以下是微软关于JOIN的文章 - http://msdn.microsoft.com/en-us/library/ms191517.aspx

答案 4 :(得分:0)

您可以使用SQL请求执行其他操作。您可以在SQL请求中加入一些,但您也可以在请求中执行另一个SELECT语句,如

SELECT SOMETHINGS FROM A_TABLE WHERE (SELECT ANOTHER_THING FROM ANOTHER_TABLE WHERE VALUE =1

但是,只有在第二次请求中有1个结果时,此声明才有效

如果你想加入两个有一些价值的表,你就必须这样做

SELECT something FROM a_table  AS alias1 JOIN another_table AS alias2 
ON alias1.value1 = alias2.value1 and .....

您可以将所需的所有值从一个表与另一个表进行比较,并且您也可以加入两个以上的表,并且您不能通过sql语法请求ON关键字

SELECT * FROM table_1 join table_2 

它会显示来自两个表的所有数据,但请确保这是您想要的数据,这种小查询会产生一些重大结果并减慢您的应用

你可以在那里阅读更多http://dev.mysql.com/doc/refman/5.0/en/join.html