簡體   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