Как избавиться от нескольких столбцов в базе данных?

В зависимости от того, где используется скрипт, он будет иметь доступ к определенным специальным переменным и полям документа. Я не знаю ваше отображение, но я думаю, что эта ссылка ответит на ваши вопросы - Доступ к полям документа и специальным переменным

Чтобы процитировать дальше ссылку выше:

Значения документа и текстовые поля

Синтаксис документа ['field'] также можно использовать для анализируемых текстовых полей, если включены данные поля, но ВНИМАНИЕ: включение данных поля в текстовом поле требует загрузки всех из терминов в кучу JVM, что может быть очень дорого как с точки зрения памяти и процессора. Редко имеет смысл обращаться к текстовым полям из сценариев.

Значения документов - это хранилище значений столбчатых полей, включенное по умолчанию для всех полей, кроме анализируемых текстовых полей.

Источник _source предоставляет доступ к индексируемому исходному телу документа (включая возможность отличать нулевые значения от пустых полей, массивы с одним значением от простых скаляров и т. Д.).

blockquote>

, если ваше поле abc является анализируемым текстовым полем или объектом, doc не будет работать.

5
задан Kredns 16 February 2010 в 05:56
поделиться

6 ответов

Excellent question Lucas, and this delves into the act of database normalization.

The fact that you recognized why having multiple columns to represent classes is bad already shows that you have great potential.

What if we wanted to add a new class? Now we have to add a whole new column. There is little flexibility for this.

So what can be done?

We create THREE tables.

One table is for students:

Student
   |-------------------------|
   | StudentID | Student_Name|
   |-------------------------|
   |     1     |     John    |
   |     2     |     Sally   | 
   |     3     |     Stan    | 
   ---------------------------

One table is for Classes:

Class
   ------------------------
   | ClassID  | Class_Name|
   ------------------------
   |    1     |   Math    |
   |    2     |   Physics |
   ------------------------

And finally, one table holds the relationship between Students and Classes:

Student_Class
   -----------------------
   | StudentID | ClassID |
   -----------------------

If we wanted to enroll John into Physics, we would insert a row into the Student_Class table.

  INSERT INTO Student_Class (StudentID, ClassID) VALUES (1, 2);

Now, we have a record saying that Student #1 (John) is attending Class #2 (Physics). Lets make Sally attend Math, and Stan attend Physics and Math.

  INSERT INTO Student_Class (StudentID, ClassID) VALUES (2, 1);
  INSERT INTO Student_Class (StudentID, ClassID) VALUES (3, 1);
  INSERT INTO Student_Class (StudentID, ClassID) VALUES (3, 2);

To pull that data back in a readable fashion, we join the three tables together:

  SELECT Student.Student_Name, 
         Class.Class_Name 
  FROM Student, 
       Class, 
       Student_Class 
  WHERE Student.StudentID = Student_Class.StudentID 
       AND Class.ClassID = Student_Class.ClassID;

This would give us a result set like this:

  ------------------------------
  | Student_Name  | Class_Name |
  ------------------------------
  |    John       |  Physics   |
  |    Sally      |   Math     |
  |    Stan       |  Physics   |
  |    Stan       |   Math     |
  ------------------------------

And that is how database normalization works in a nutshell.

18
ответ дан 18 December 2019 в 05:40
поделиться

This is a normalisiation issue. In effect you are asking the wrong question. In stead ask yourself the question how can you store 0 or more classes_taken? What other details do you need to store about each class taken? E.g. just the class taken, or data taken, result, etc?

For example consider somethin like the following

table Student
 id int
 name varchar(25)
 ...

table classes
 id int
 name varchar(25)
 ...

table clases_taken
 student_id int (foreign key to student.id)
 class_id int (foreign key to class.id)
 data_started datatime
 result varchar(5)
 tutor_id int (foreign key to tutor.id)
 ...

2
ответ дан 18 December 2019 в 05:40
поделиться

Похоже, вам нужно подумать о нормализации схемы вашей базы данных.

Существует отношение «многие ко многим» между учащимися и классами, так что многие учащиеся могут принять многие классы могут посещать многие и многие классы. Наиболее распространенным подходом к обработке этого сценария является использование соединительной таблицы .

Что-то вроде этого

Student Table
-------------
id
first_name
last_name
dob

Class Table
-----------
id
class_name
academic_year

Student_Class Table
-------------------
student_id
class_id
year_taken

Тогда ваши запросы будут объединяться в таблицах, например,

SELECT
    s.last_name + ', ' + s.first_name AS student_name,
    c.class_name,
    sc.year_taken
FROM
    student s
INNER JOIN
    student_class sc
ON
    s.id = sc.student_id
INNER JOIN
    class c
ON
    sc.class_id = class.id
ORDER BY
    s.last_name, sc.year_taken

Одно слово совета, которое Я хотел бы упомянуть, что Access требует от вас использовать круглые скобки при соединении в запросе не только таблицы, я полагаю, это потому, что он требует от вас указать порядок, в котором они должны быть присоединены. Лично я нахожу это неловким, особенно когда я привык писать много SQL без дизайнеров. В Access я бы рекомендовал использовать конструктор для объединения таблиц, затем измените сгенерированный SQL для ваших целей.

4
ответ дан 18 December 2019 в 05:40
поделиться

So you have 15 columns (e.g. class1, class2, class3 ... class15)?

Looks like you have a classic many-to-many relationship. You should create a new table to relate students and classes.

student { StudentID, StudentName ... }
classes { ClassID, ClassName ... }
student_classes { StudentID, ClassID }

If you are tracking classes on a year-by-year basis, you could add a year column to the relationship as well:

student_classes { StudentID, Year, ClassID }
4
ответ дан 18 December 2019 в 05:40
поделиться

У вас никогда не должно быть столбцов, таких как class1, class2, class3, class4 и т. Д. В таблице базы данных. То, что вы должны иметь, это связанная таблица. Ваша структура будет выглядеть примерно так:

Student Table with the following columns
StudentID
StudentLastName
StudentFirstName 
(and so forth for all the data to describe a student)

Затем

Course table with the following columns
CourseId
CourseName

Затем

StudentCourse Table with the following columns
StudentId
CourseID
CourseDate

Теперь, чтобы узнать, какие курсы посещал человек, вы присоединитесь к этим столам вместе. Примерно так:

Select StudentID,StudentLastName,StudentFirstName, CourseName, CourseDate
from Student 
join StudentCourse on student. studentid = StudentCourse.StudentID
join Course on Course.courseID = StudentCourse.CourseID 

Пожалуйста, прочитайте эту ссылку, чтобы начать изучение основ базы данных: http://www.deeptraining.com/litwin/dbdesign/FundamentalsOfRelationalDatabaseDesign.aspx

2
ответ дан 18 December 2019 в 05:40
поделиться

How about no class columns in the student table. Setup a new table with student id and class id columns. Each row represents a class the student took. Maybe add more columns such as: the year/semester, grade, etc.

1
ответ дан 18 December 2019 в 05:40
поделиться
Другие вопросы по тегам:

Похожие вопросы: