如何检索与 SQL 查询顺序不同的数据?

发布于 2024-10-05 10:29:07 字数 315 浏览 10 评论 0原文

我正在尝试从 SQL 中的表中检索记录。

这就是我想要的。例如:

我有一个名为 StudentScore 的表,其中有两列:

studentName -----  Scores
John Smith  ----- 75,83, 96

我想这样做:当我在搜索框中输入分数时,我希望它显示学生的姓名。例如:我可以输入“83,96,75”(分数可以按任何顺序),这应该显示学生姓名“John Smith”。但我想知道如果我们在框中键入的内容与列中原始数据的顺序不同,我们如何在 WHERE 子句中指定以便它选取正确的记录?

I am trying to retrieve a record from a table in SQL.

Here is what I want. For example:

I have a table name studentScore with two columns:

studentName -----  Scores
John Smith  ----- 75,83, 96

I want to do this: When I type the score in a search box, I want it to show me the name of the student. For example: I could type "83, 96, 75", (the scores can be in any order) and this should show me the student name "John Smith". But I'm wondering how we could specify in the WHERE clause so that it picks up the correct record, if what we type in the box is not in the same order as the original data in the column?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

倾城泪 2024-10-12 10:29:07

您的问题是您的数据未正确标准化。您将 1 对 n 关系放入单个表中。如果您要像这样重新组织表:

Table Students

id  name
1   John Smith

Table Scores

studentId score
1         75
1         83
1         96

您可以执行如下查询:

select st.name from Students st, Score sc where st.id = sc.studentId and sc.score in ("83", "75", "96")

如果您想做其他查询(例如找出哪些学生的分数至少为 X),这也会有所帮助,否则这对于现有表来说是不可能的布局。

如果您必须坚持现有的布局(我不建议这样做),但是您可以拆分用户输入,然后执行类似的查询,

select from studentScore where score like '%75%' or score like '%83%' or score like '%96%'

但我真的会避免这样做。

Your issue is that your data is not properly normalized. You are putting a 1 to n relationship into a single table. If you'd reorganize your tables like such:

Table Students

id  name
1   John Smith

Table Scores

studentId score
1         75
1         83
1         96

You could do a query like:

select st.name from Students st, Score sc where st.id = sc.studentId and sc.score in ("83", "75", "96")

This also helps if you want to do other queries, like find out which students have a score of at least X, which would be otherwise impossible with your existing table layout.

If you must stick with your existing layout, which I don't recommend, however you could split up the user input and then do a query like

select from studentScore where score like '%75%' or score like '%83%' or score like '%96%'

But i really would refrain from doing so.

征﹌骨岁月お 2024-10-12 10:29:07

我认为这是可以解决的,但如果每个学生的分数存储为单独的行,例如存储在 scores 表中,事情会更简单。否则,代码必须将条目排列成每个可以想象的顺序。或者分数条目必须以某种方式按照标准顺序。

I suppose it is solvable, but it would be simpler if the scores for each student were stored as separate rows, for example in a scores table. Otherwise, the code would have to permute the entry into every conceivable order. Or the scores entry would have to be in a standard order somehow.

巴黎盛开的樱花 2024-10-12 10:29:07

如果您不想为分数创建新表(例如使用 StudentId、分数列),您可以在存储之前对数字进行排序。

这样,当有人输入查询时,您也会对这些数字进行排序,并将其与存储的字符串进行比较。

如果您需要分数的原始位置,可以将它们存储在单独的字段中。

If you do not want to create a new table for Scores, - e.g. with StudentId, Score columns -, you may sort the numbers before storing them.

This way, when someone types a query, you sort those numbers as well and just compare it to the stored strings.

If you need the original position of the scores, you can store those in a separate field.

芸娘子的小脾气 2024-10-12 10:29:07

改进您的数据库架构...这甚至不能满足第一个范式(http://en. wikipedia.org/wiki/Database_normalization#Normal_forms)。

改进架构将在未来为您省去很多麻烦(源于更新异常)。

Improve your database schema...this does not satisfy even the first normal form (http://en.wikipedia.org/wiki/Database_normalization#Normal_forms).

Improving the schema will save you plenty of headaches in the future (stemming from update anomalies).

被你宠の有点坏 2024-10-12 10:29:07

任何 SQL 表都不应该有多个属性值(在同一列中)。分数是否存储为字符串?如果是这样,您的查询将更加复杂,并且您浪费了数据库的点。

但是,对于您的问题:

SELECT col4, col3, col2 FROM students WHERE col1 = 57; 

这将按顺序 (4,3,2) 返回第 4、3 和 2 列,即使它们按 1、2、3、4 的顺序保存。SQL 返回您要求的内容您要求的顺序。

No sql table should have multiple values for an attribute (in the same column). Are the scores stored as a string? If so, your query will be more complicated and you're wasting the point of the DB.

however, to your question:

SELECT col4, col3, col2 FROM students WHERE col1 = 57; 

this will return columns 4, 3, and 2 in that order (4,3,2) even if they are saved in the order 1, 2, 3, 4. SQL returns the things you ask for in the order you ask for them.

套路撩心 2024-10-12 10:29:07

所以是的,我同意其他人的观点,这个设计很糟糕。如果您正确地规范化该表,您将能够非常轻松地获得所需的数据。

但是,这就是您可以使用当前结构实现的方式。将用户输入拆分为离散分数。然后,将每个值传递到过程中。

CREATE PROCEDURE FindStudentByScores
    (
     @score1 AS VARCHAR(3) = NULL
    ,@score2 AS VARCHAR(3) = NULL 
    ,@score3 AS VARCHAR(3) = NULL 
    )
AS 
    BEGIN
        SELECT  *
        FROM    [Students]
        WHERE   ( @score1 IS NULL
                  OR [Scores] LIKE '%' + @score1 + '%' )
                AND ( @score2 IS NULL
                      OR [Scores] LIKE '%' + @score2 + '%' )
                AND ( @score3 IS NULL
                      OR [Scores] LIKE '%' + @score3 + '%' )

    END 

So yeah, I agree with everyone else that this design is crap. If you were to normalize this table properly, you would be able to very easily get the data you need.

However, this is how you could do it with the current structure. Split the user input into discrete scores. Then, pass each value into the procedure.

CREATE PROCEDURE FindStudentByScores
    (
     @score1 AS VARCHAR(3) = NULL
    ,@score2 AS VARCHAR(3) = NULL 
    ,@score3 AS VARCHAR(3) = NULL 
    )
AS 
    BEGIN
        SELECT  *
        FROM    [Students]
        WHERE   ( @score1 IS NULL
                  OR [Scores] LIKE '%' + @score1 + '%' )
                AND ( @score2 IS NULL
                      OR [Scores] LIKE '%' + @score2 + '%' )
                AND ( @score3 IS NULL
                      OR [Scores] LIKE '%' + @score3 + '%' )

    END 

您可以使用正则表达式或 Like 运算

符 正则表达式解决方案可能看起来像

SIMILAR TO '%(SCORE1|SCORE2|SCORE3)%' 

这是最简单的方法
但我建议您更改现在提到的整个表结构
几次,因为您无法利用索引或键
几十个访问者就会耗尽计算机的资源

You could use Regular expressions or the Like operator

A regexp solution could look like

SIMILAR TO '%(SCORE1|SCORE2|SCORE3)%' 

That's the easiest way to go
but I recommend you changing your entire table structure as been mentioned now
a couple of times, since you have no possibility to take advantage of an index or key
which will exhaust the computer in matter of a couple tens of visitors

江南烟雨〆相思醉 2024-10-12 10:29:07

这是一个数据库规范化对您有很大帮助的示例。

你可以像这样存储你的数据
编辑:如果您想保持顺序,您可以添加顺序列)

studentName        Scores    Order
John Smith         75        1
John Smith         83        2
John Smith         96        3
Foo bar            73        1
Foo bar            34        2
........

但是,如果您坚持使用当前模型,您的下一个最佳选择是对分数列进行排序,那么您只需要从文本框中取出搜索字符串,正确排序并格式化,然后就可以搜索了。

最后,如果分数未在表中排序,您可以创建所有可能的组合

75, 83, 96
75, 96, 83
83, 75, 96
83, 96, 75
96, 75, 83
96, 83, 75

并使用 OR 搜索它们。

This is an example of where database normalization should help you a lot.

You could store your data like this
(Edit: if you want to keep the order you can add an order column)

studentName        Scores    Order
John Smith         75        1
John Smith         83        2
John Smith         96        3
Foo bar            73        1
Foo bar            34        2
........

But if you are stuck with the current model your next best option is to have the Scores column sorted, then you just need to take the search string from the textbox, sort and format it correctly, then you can search.

Lastly if the scores is not sorted in the table you can create all possible combinations

75, 83, 96
75, 96, 83
83, 75, 96
83, 96, 75
96, 75, 83
96, 83, 75

and search for them all with OR.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文