开发者

Searching returned records in MySQL

开发者 https://www.devze.com 2023-04-13 00:40 出处:网络
Consider the following table structure (not designed by me, and 开发者_运维问答unchangable): +---------------+-----------------------------+---------------------------+

Consider the following table structure (not designed by me, and 开发者_运维问答unchangable):

+---------------+-----------------------------+---------------------------+
|    the_id     |         field_name          |        field_value        |
+---------------+-----------------------------+---------------------------+
|      1        |           county            |       lincolnshire        |
|      1        |            type             |           hotel           |
|      2        |           county            |       lincolnshire        |
|      2        |            type             |          castle           |
+---------------+-----------------------------+---------------------------+

Basically, I want to perform a search on this data, returning the_id of anything that matches the parameters I specify. So, for example I want to search for all the_id fields which have (field_name = county AND field_value = lincolnshire) AND (field_value = type AND field_value = castle). Thus, only 1 would be returned.

Essentially, I want to know if it's possible to perform a search on the returned results. Since the fields are completely separate entities linked by the_id, here's what I'm thinking in pseudo-code:

  • Look up county
  • Search for the_id and type in the results
  • Return sub-set.

The problem is, I'm not 100% sure how this could be implemented in MySQL. Any feedback would certainly be gratefully received!


Ah, the joys of using an SQL database as key-value stores, because it makes the DB schema so much simpler... first off, take the original designer of this system out back and beat them up with a rotten wet fish, preferably whale-sized, dropped from a great height.

then...

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'


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'


Combine the Select and Where commands to run a query. http://www.w3schools.com/sql/sql_select.asp

0

精彩评论

暂无评论...
验证码 换一张
取 消