考虑以下表格结构(不是我设计的,不可变的):
+---------------+-----------------------------+---------------------------+
| the_id | field_name | field_value |
+---------------+-----------------------------+---------------------------+
| 1 | county | lincolnshire |
| 1 | type | hotel |
| 2 | county | lincolnshire |
| 2 | type | castle |
+---------------+-----------------------------+---------------------------+
基本上,我想对此数据执行搜索,返回与我指定的参数匹配的任何内容的the_id
。因此,例如,我想搜索具有(field_name = county AND field_value = lincolnshire)AND(field_value = type AND field_value = castle)的所有the_id
字段。因此,只返回1个。
基本上,我想知道是否可以对返回的结果执行搜索。由于这些字段是由the_id
链接的完全独立的实体,所以这就是我在伪代码中的想法:
county
the_id
和type
问题是,我不是100%确定如何在MySQL中实现这一点。肯定会感激地收到任何反馈!
答案 0 :(得分:3)
SELECT t1.the_id
FROM YourTable t1
INNER JOIN YourTable t2
ON t1.the_id = t2.the_id
WHERE t1.field_name = 'county'
AND t1.field_value = 'lincolnshire'
AND t2.field_name = 'type'
AND t2.field_value = 'castle'
答案 1 :(得分:3)
啊,使用SQL数据库作为键值存储的乐趣,因为它使数据库架构变得如此简单......首先,将该系统的原始设计者带回来并用腐烂的湿殴打它们鱼,最好是鲸鱼大小,从高处掉下来。
...然后
SELECT the_id, type, county
FROM (
SELECT type_name.the_id AS the_id, type.field_value AS type, county.field_value AS county
FROM yourtable AS type
LEFT JOIN yourtable AS county ON county.the_id = type.the_id AND county.field_name='county'
WHERE type.field_type = 'type'
) AS child
WHERE county='lincolnshire'
答案 2 :(得分:0)
组合Select和Where命令以运行查询。 http://www.w3schools.com/sql/sql_select.asp