Single SQL statement - is it possible?
I can't seem to work this out, in the past I would usually do this with multiple SQL statements and join the data with PHP. I'm aware that this is not the best way to program though so I'd like to try to get all my data with one SQL statement.
Here are the tables.
table pages:
id name fields
1 home 1,3,4
table data_fields:
id field
1 title
2 subtitle
3 description
4 image
table page_data:
id title subtitle description image link quote
1 Hello null de开发者_运维问答scriptionText null null null
So basically I want to pull the page data depending on the page id.
How do I split up the pages.fields
field that is separated with commas then get the fields required from data_fields
and then pull the data from page_data
depending on the field name retrieved from data_fields?
Under the relational model, domains should be simple; this is called "first normal form". In plainer terms, don't pack multiple values in a single column. Normalize the pages
table by breaking up the fields
column into another table. For example,
CREATE TABLE page_fields {
page INT UNSIGNED,
field INT UNSIGNED,
FOREIGN KEY `page` REFERENCES `pages` (id),
FOREIGN KEY `field` REFERENCES `data_fields` (id)
} Engine=InnoDB;
Then join the pages
, data_fields
and page_data
tables using page_fields
.
Alternatively, restructure the page_data
table and do away with data_fields
:
CREATE TABLE page_data {
page INT UNSIGNED,
name ENUM('title', 'subtitle', 'description', 'image', 'link', 'quote'),
data VARCHAR(...),
FOREIGN KEY page REFERENCES pages (id)
} Engine=InnoDB;
then join pages
with page_data
.
nothing personal, but your design is redundand and poor. if you want, we can help you to reorganize you database structure. I don't actually understand, why do you want to keep several tables? all the attributes you've counted belong to a single entity. there is no many-to-one, many-to-many relations, so it can be described in a single table, eg:
create table PAGES (
id int not null,
title varchar(256) null,
subtitle varchar(256) null,
description varchar(1024) null,
image blob null,
link varchar(256) null,
quote varchar(256)
)
if the page does not have some attribute (title or drescription, etc) this field is just NULL, and you will keep it in mind when will process this information within php-script.
Your database is not designed well. Repeating groups within columns are a PITA to work with. You should refactor your database design and then use Joins.
精彩评论