简体   繁体   中英

In this table structure, how to search for articles by field values?

Among the joomla tables there are these three tables, content that stores the articles, fields that stores the definition of custom fields and fields_values that stores the values assigned to these custom fields in articles.

Here the table definitions with some of their fields

content
-------------
  id
  title

fields
-------------
  id
  title
  name

fields_values
-------------
  field_id <-- field_id refer to content id
  item_id
  value

I need to search content records for the values in field_values, but I don't know how to do it

For convenience I created this sqlfiddle

The sqlfiddle with the value target

Given the sqlfiddle sample data I need to search for the articles (content records) where any of the fields have the value target

The expected results would be the article with id 1 because in field1 of article 1 has the value target and the article with id 3 because in field2 of article 3 has the value target

I appreciate your advice...

You need to join fields table to fields_values table using field_id and join this joint table to content using fields_values.item_id .

Then in where clause you can give values for fields.title and field_values.value to get columns from content table.

There will be duplicates from content table. So you can select with distinct or you can group by in content table:

SELECT DISTINCT c.id, c.title FROM fields f 
  join fields_values v on f.id=v.field_id 
  join content c on c.id=v.item_id
  WHERE f.title='{field_title}' and v.value='{value}'

Although not a part of question. Without proper indexing this schema will not scale very well with big data. I suggest to optimize indexing on all tables, especially index columns.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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