繁体   English   中英

如何比较两个表中的数据并显示一个表中的数据

[英]How to compare data in two tables and display data from one table

我有2个具有以下结构的表:

categories
    id
    status
    name
    created
posts
    id
    status
    category_id
    title
    excerpt
    featured_image
    created
user_authors
    id
    status
    author_name
    created

我正在使用以下查询:

$query = "SELECT posts.id, posts.category_id, user_authors.author_name, posts.user_author_id, posts.title, posts.post_slug, posts.featured_image, posts.excerpt, posts.created FROM posts, user_authors INNER JOIN categories ON(posts.category_id = categories.id) WHERE posts.status = 1 AND categories.name LIKE = %".$_GET['category']."%";

我想做的是,我有一个网址www.xyz.com/technology

技术是其中的一个参数(类别),我将选择要显示的帖子。

我正在显示数据,其中posts.category_id = categories.id AND category_name = $_GET['category']

我无法提取任何数据,我很困惑我的查询错误还是逻辑错误?

谁能帮助我解决这个逻辑?

您不能在LIKE子句中使用= ,并且您没有在postsuser_authors表之间编写任何关系。

正确的查询应为:

$query = "SELECT posts.id, posts.category_id, user_authors.author_name, posts.user_author_id, posts.title, posts.post_slug, posts.featured_image, posts.excerpt, posts.created FROM posts INNER JOIN user_authors ON (user_authors.id = posts.user_author_id) INNER JOIN categories ON (posts.category_id = categories.id) WHERE posts.status = 1 AND categories.name LIKE '%".$_GET['category']."%'";

如果只查找一个categories.name ,则可以从查询中删除% ,这将有助于mysql如果categories.name列具有索引,则可以搜索记录。

您的查询中带有=LIKEmysql中不正确。 正确的方法应该是

categories.name LIKE '%". $_GET['category']."%'"

注意删除=并用'括起来


编辑:

根据您的答复,新查询应如下所示。

SELECT posts.id, posts.category_id, user_authors.author_name, posts.user_author_id, posts.title, posts.post_slug, posts.featured_image, posts.excerpt, posts.created 
FROM posts INNER JOIN categories ON posts.category_id = categories.id
INNER JOIN user_authors ON posts.id = user_authors.id 
WHERE posts.status = 1 AND categories.name LIKE '%".$_GET['category']."%'"

考虑从选择中删除user_author,因为没有联接可以链接命令中的三个表。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM