我是SQL和PHP的新手。我有一个要求,即最终用户在HTML表单中输入文本,我将其存储在MySQL数据库中。稍后我查询db中具有用户数据的所有表以获取连接字符串。
为了更清楚地理解,这里是我的数据和所需结果的图像:Click for Image
现在我能够根据具有此查询的特定ID连接一个字符串:
select group_concat(text order by T.did separator ' ') as TTT
from (
select l.dimgroupid as did, d.*, l.dimlevelid as id, l.dimlevelvalue,
concat(d.dimensiontext," ",l.dimlevelvalue) as text
from dimensionlevel l
join dimension d on d.dimensionid = l.dimid
join dimensiongroup g on g.groupid = l.dimgroupid) as T
where T.id=0;
给我结果
| TTT |
--------------------------------
| A 20 year old Man is Fresher |
我知道我可以在id上使用循环,但问题是id不固定。
注意:可以有" n"维度和级别数。
以下是我要查询的数据的SQL小提琴:SQL Fiddle
答案 0 :(得分:0)
我已经编辑了您的查询以获得您想要的内容..
select did as groupid, group_concat(text order by dimensionid separator ' ' ) as TTT
from (
select l.dimgroupid as did, d.*, l.dimlevelid as id, l.dimlevelvalue, concat(d.dimensiontext," ",l.dimlevelvalue) as text
from dimensionlevel l
join dimension d on d.dimensionid = l.dimid
join dimensiongroup g on g.groupid = l.dimgroupid
) as T
group by id;
我希望这可以帮助你...
更新: 使用php ..
$sql = "SELECT `dimensionid`, `dimensiontext`, `dimensiondescr` FROM `dimension`";
$dimensions = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='age') ";
$ages = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='sex') ";
$sexes = mysqli_fetch_all (mysqli_query($con, $sql));
$sql = "SELECT `dimlevelvalue` FROM `dimensionlevel` WHERE dimid IN (SELECT dimensionid FROM dimension WHERE dimensiondescr='experience') ";
$experiences = mysqli_fetch_all (mysqli_query($con, $sql));
foreach ($ages as $age) {
foreach ($sexes as $sex) {
foreach ($experiences as $exp) {
foreach ($dimensions as $dimension) {
$putage = "";
$putsex = "";
$putexp = "";
if($dimension[2]=="Age"){
$putage = $age[0];
}elseif($dimension[2]=="Sex"){
$putsex = $sex[0];
}elseif($dimension[2]=="Experience"){
$putexp = $exp[0];
}
echo $str = $dimension['1']." ".$putage.$putsex.$putexp." " ;
}
echo "<br>";
}
echo "<br>";
}
}