简体   繁体   English

在SQL查询中联接表以进行搜索

[英]Joining tables in sql query for a search

Alright this is a total mess and I'm so lost right now. 好吧,这真是一团糟,我现在迷失了。 I'm trying to have a search for a site in which you can search for a word and it will go through a table called designs to search the table through multiple columns for the word. 我正在尝试搜索一个可以在其中搜索单词的网站,它将通过一个名为designs的表来搜索该表中的多列单词。 I had that working until I decided that I would like the option to also search for the username of another member. 我一直在努力,直到我决定我还希望该选项还搜索另一个成员的username in the design table, there is a column named user in which that matches up with the id inside of users . design表中,有一列名为user的列,其中与users内的id匹配。 I hope that makes sense because I really don't want to have to draw out a table.. 我希望这是有道理的,因为我真的不想画一张桌子。

$result = mysql_query("
SELECT designs.*, users.* 
FROM designs, users 
WHERE type LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR title LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR tags LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR description LIKE '%" . mysql_real_escape_string($search1) . "%' 
OR users.username = " . mysql_real_escape_string($search1) . " 
ORDER BY designs.id 
DESC
");

This is what it currently looks like, and $search1 is what the user is searching.. I want to be able to display any designs that a user has made by searching for the username of the user after connecting the designs.user to users.id but it just won't work, any ideas? 这是当前的样子, $search1是用户正在搜索的内容。我希望能够在将designs.user连接到用户之后通过搜索username的用户username来显示用户所做的任何designs users.id但它行不通,有什么想法吗?

ALSO mysql_error() gives me the error that "Unknown column 'namehere' in 'where clause'" mysql_error()给我这样的错误:“'where子句'中的未知列'namehere'”

The query for inner join is this, and you have to specify the table name like designs.<columnname> to query them. 内部联接的查询是这样的,您必须指定表名(如designs.<columnname>才能对其进行查询。

    SELECT designs.*, users.* 
    FROM designs
    INNER JOIN users on users.id = designs.user
    WHERE designs.type LIKE '%<SEARCH TEXT>%' 
    OR desings.title LIKE '%<SEARCH TEXT>%' 
    OR designs.tags LIKE '%<SEARCH TEXT>%' 
    OR designs.description LIKE '%<SEARCH TEXT>%' 
    OR users.username = '<USER ID>' 
    ORDER BY designs.id 
    DESC

Simple syntax is 简单的语法是

INNER JOIN <table name> <alias> ON <first table>.<column name> = <second table>.<column name>

HUGE Problem is you are using mysql_* API, please these method are very vulnerable Do not USE them 巨大的问题是您正在使用mysql_* API,请这些方法非常容易受到攻击, 请勿使用

If you use other API like mysqli or PDO, you dont have to use mysql_real_escape_string to make your query safe. 如果您使用mysqli或PDO等其他API,则不必使用mysql_real_escape_string来确保查询安全。

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

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