PHP MySQL查询:根据帖子ID获取类别名称?

时间:2015-11-03 15:45:26

标签: php mysql

posts表:

id | name              | category_id
1  | Some article name |   3

categories表:

id | name
3  | Some Category name

...

$sql = '';

$query = DB::query($sql, $post_id);

foreach ($query as $row){
        $category_name = $row["name"];
    }

$ sql应该包含什么才能让查询完成工作?

2 个答案:

答案 0 :(得分:1)

SELECT c.name
FROM posts p
INNER JOIN categories c ON c.id = p.category_id
WHERE p.id = ...

答案 1 :(得分:1)

$query="SELECT * FROM posts po join categories cat on (cat.id=po.category_id) WHERE po.id=$post_id"