本文介绍了SQL选择字符串不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经发布了此信息,但我想对其进行更好的解释.我有一个网站,学生可以在其中插入他们的4门课程和每门课程的4条评论,这些是SQL表列:课程1,课程2,课程3,课程4,注释1,注释2,注释3,注释4.

I've already posted this but I want to explain it better. I have a website in which students insert their 4 courses and 4 comments for each course, these are the SQL table columns:Course1, Course2, Course 3, Course 4, Comment1, Comment2, Comment 3, Comment 4.

我有一个搜索,其中有任何学生输入,例如,地理位置(可以保存在四个课程列中的任何一列中),并且我希望我的SQL查询返回针对地理位置的所有注释.例如,如果某个学生将地理位置"保存在课程2"的位置,我希望我的SQL查询选择评论2",其中课程2 =地理位置".他可能已经将其保存在课程1中,因此它必须灵活,但只能选择学生选择的课程.这是我当前的SQL查询:

I have a search in which any student inputs, for instance, geography (which may be saved in any of the four course columns), and I want my SQL query to return all the comments for geography. For example, if a student saved Geography in position Course2, I want my SQL query to select comment2 where course2 = geography. He may have saved it in course1, so it has to be flexible, but only select the course chosen by the student. This is my current SQL query:

$SQL = "SELECT (Comment1 FROM Students WHERE Course1 = 'geography'), (Comment2 FROM Students WHERE Course2 = 'geography'), (Comment3 FROM Students WHERE Course3 = 'geography'),  (Comment4 FROM Students WHERE Course4 = 'geography')";

当前,此SQL查询无法正常工作.我知道该结构可能看起来很奇怪,但是正如您可能理解的那样,从逻辑上讲,这是有道理的,尽管这可能不是正确的编码方式.然后,我将打印所有的地理注释,如下所示:

Currently, this SQL query isn't working.I know the structure may seem odd, but logically, as you may understand, this makes sense, though it's probably not the right way to code it. I then print all the geography comments like this:

$null = '';
if(mysql_num_rows($result)) {
  echo "<ol>";
 while ($row=mysql_fetch_array($result)) {
  if($row["Class"]!=$null) {
  if($null!='') {
  echo "</ol><ol type='1'>";
  }
 }

 echo "<li><p>" . " " . $row["Comment1"]. " " . $row["Comment2"]." " .    $row["Comment3"] . " " . $row["Comment4"] . "</li></p>";
$i = $i +1;
}

echo "</ol>";

推荐答案

假定表结构真的不能更改(不再),我将使用 UNION 此处

Assuming that table structure really(sic) can't be changed (anymore) I'd go with a UNION here

    ( SELECT Comment1 as comment FROM soFoo WHERE Course1='geography' )
UNION ALL
    ( SELECT Comment2 as comment FROM soFoo WHERE Course2='geography' )
UNION ALL
    ( SELECT Comment3 as comment FROM soFoo WHERE Course3='geography' )
UNION ALL
    ( SELECT Comment4 as comment FROM soFoo WHERE Course4='geography' )

它给MySQL至少一个使用索引查找匹配记录的机会.

It gives MySQL at least a fighting chance to use indices to find the matching records.

这篇关于SQL选择字符串不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-25 13:09