简体   繁体   English

高级搜索功能-SQL

[英]Advanced Search Functionality - SQL

i'm working on an advanced search functionality on my website. 我正在网站上使用高级搜索功能。 Basically data I'm working on is stored within two tables. 基本上,我正在处理的数据存储在两个表中。

First table contains basic information about the product (1 row = 1 product so it's unique). 第一个表包含有关产品的基本信息(1行= 1个产品,因此它是唯一的)。 Table structure may look like this: 表结构可能如下所示:

id, title, description

The second table contains more information about the product. 第二张表包含有关产品的更多信息。 The product may but don't have to have any rows here. 该产品可能但不必在这里有任何行。 However, one product may store in the second table a few rows. 但是,一种产品可以在第二个表中存储几行。 What's more - data in the second table should be used to the advanced search functionality. 而且,第二张表中的数据应用于高级搜索功能。 Table structure may looks like this: 表结构可能如下所示:

id, item_id (from table 1), value_id (from another table), value

I want to select only these products (table 1) which has specified value_id (from column 2): 我只想选择已指定value_id的这些产品(表1)(来自第2列):

... WHERE table1.item_id = 5 AND table2.value_id = 1000

As I mentioned before - table 2 may but doesn't have to contains any rows connected by item_id with the table 1. 正如我之前提到的,表2可以但不必包含由item_id与表1连接的任何行。

I've tried to use JOIN/LEFT JOIN function in SQL but in this case when the product has 3 rows in the table 2 - a query result returns 3 rows instead of 1 or 0 (if not found any results). 我试图在SQL中使用JOIN / LEFT JOIN函数,但是在这种情况下,当产品在表2中有3行时-查询结果将返回3行而不是1或0(如果未找到任何结果)。

How can I handle that? 我该如何处理?

You want to select products. 您要选择产品。 So select from the product table. 因此,请从产品表中选择。 You want to select only those for which exists a certain attribute. 您只想选择那些存在特定属性的属性。 So create an approriate WHERE clause. 因此,创建一个适当的WHERE子句。 As you want to look up data in another table, you could use EXISTS or IN . 当您想在另一个表中查找数据时,可以使用EXISTSIN

select *
from items
where id in (select item_id from item_values where value_id = 1000);

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

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