简体   繁体   English

MySQL:选择与多行匹配的项目

[英]MySQL: Select an item that matches multiple rows

I have a few (over 20) tables in MySQL, which describe an item on many different levels (colors, location etc.). 我在MySQL中有几个(超过20个)表,它们在许多不同的级别(颜色,位置等)描述一个项目。 The following is an example of "table01" 以下是“ table01”的示例

+----+----------+
| ID | property |
+----+----------+
|  1 | A        |
|  1 | B        |
|  2 | C        |
|  2 | B        |
+----+----------+

Now I want to search for items that match multiple criteria. 现在,我要搜索符合多个条件的项目。 The following query works just fine 以下查询工作正常

SELECT
  table01.ID, table01.property, table02.property, table03.property [...]
FROM
  table01
LEFT JOIN table02 ON table02.ID = table01.ID
LEFT JOIN table03 ON table03.ID = table01.ID
[...]
WHERE
  table01.property = "A"
  and table02.property = "B"
  and table03.property = "A"
  [...]

Heres my problem. 这是我的问题。 I want to search for an item that matches for a few properties in one table. 我想在一个表中搜索与几个属性匹配的项目。 For example (this query obviously does not work) 例如(此查询显然不起作用)

table01.property = "A" AND table01.property = "B"

I don't know how to achieve that, because the information is stored in multiple rows. 我不知道如何实现,因为信息存储在多行中。

Any suggestions? 有什么建议么? The database is huge (a few thousand entries per table) and new rows get added from time to time. 数据库非常庞大(每个表有数千个条目),并且不时添加新行。 Should I do some of the processing through PHP or is there a pure MySQL Solution? 我应该通过PHP进行一些处理还是有一个纯MySQL解决方案?

You could achieve this, for example, by doing 例如,您可以通过执行

SELECT ID,count(property) AS CNT FROM table01 
WHERE property = 'A' OR  property = 'B'
GROUP BY ID
HAVING CNT=2;

This will give you list of IDs who have both properties. 这将为您提供具有这两个属性的ID列表。

However, it can grow more convoluted with more properties to check for AND unwieldy with more tables. 但是,随着更多的属性来检查和检查更多表的复杂性,它会变得越来越复杂。 If at all possible, it might be more useful to rethink your database schema to at least have a single table with properties, not multiple. 如果有可能,重新考虑数据库架构,使其至少具有一个具有属性而不是多个属性的表可能会更有用。

You can use query given by @Gnudiff with your query as follows: 您可以将@Gnudiff给出的查询与查询一起使用,如下所示:

SELECT
  table01.ID, table01.property, table02.property, table03.property [...]
FROM
  (SELECT *FROM table01 
   WHERE property = 'A' OR  property = 'B'
   GROUP BY ID
   HAVING count(property)=2) as table01
LEFT JOIN table02 ON table02.ID = table01.ID
LEFT JOIN table03 ON table03.ID = table01.ID
[...]
WHERE
  table02.property = "B"
  and table03.property = "A"
  [...]

Click here for Demo 单击此处进行演示

Hope it helps! 希望能帮助到你!

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

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