I have the following query:
SELECT u.uid, pf.title, pv.value FROM users AS u INNER JOIN
profile_values AS pv ON pv.uid = u.uid
INNER JOIN
profile_fields AS pf ON pf.fid = pv.fid
ORDER BY u.uid
Which results in:
uid title value
1 First name Jared
1 Last name Boo
1 Organization Acme
1 Website http://acme.com
1 Country Canada
6 First name Nathan
6 Last name Foo开发者_开发技巧
I am attempting to use this result to create another result set which looks like this:
uid First name Last name Organization Website Country
1 Jared Boo Acme http... Canada
6 Nathan Foo
Am I going about this correctly?
Thanks in advance
EDIT
Tables:
CREATE TABLE `users` (
`uid` int(10) unsigned NOT NULL auto_increment,
`name` varchar(60) NOT NULL default '',
`pass` varchar(32) NOT NULL default '',
`mail` varchar(64) default '',
`created` int(11) NOT NULL default '0',
`access` int(11) NOT NULL default '0',
PRIMARY KEY (`uid`),
UNIQUE KEY `name` (`name`),
KEY `access` (`access`),
KEY `created` (`created`),
KEY `mail` (`mail`)
);
CREATE TABLE `profile_fields` (
`fid` int(11) NOT NULL auto_increment,
`title` varchar(255) default NULL,
`name` varchar(128) NOT NULL default '',
`explanation` text,
`category` varchar(255) default NULL,
PRIMARY KEY (`fid`),
UNIQUE KEY `name` (`name`),
KEY `category` (`category`)
);
CREATE TABLE `profile_values` (
`fid` int(10) unsigned NOT NULL default '0',
`uid` int(10) unsigned NOT NULL default '0',
`value` text,
PRIMARY KEY (`uid`,`fid`),
KEY `fid` (`fid`)
);
SELECT u.uid, pf.title, pv.value
FROM users AS u, profile_values AS pv, profile_fields AS pf
WHERE pv.id = u.uid, pf.fid = pv.fid
ORDER BY u.uid
Is something like this what your looking for? What do the tables look like in terms of foreign keys? You may want to throw a DISTINCT
in right after SELECT
.
This is all correct. It is not clear where organization, Website, Country fields should come from (as we don't know your database structure), but, for example, if country
was a column of profile_fields
, you would simply add SELECT ..., pf.country ...
to get the desired data.
It seems like your schema is not accurately maintaining the required information. First off in the User
table you have name as 1 attribute, thus splitting first and last name must be done by some other means. Secondly it is not clear where the company name or website information is stored. Please provide a logical mapping from the desired output to the attributes in the database tables.
精彩评论