SELECT
lesson_id_1,
lesson_id_2,
lesson_id_3,
lesson_id_4,
lesson_id_5,
lesson_id_6,
lesson_id_7,
lesson_id_8,
lesson_id_9,
lesson_id_10
FROM hub_attendance
WHERE
student_id='351' AND
course_id = '102' AND
(
lesson_id_1 = 300 OR
lesson_id_2 = 300 OR
lesson_id_3 = 300 OR
lesson_id_4 = 300 OR
lesson_id_5 = 300 OR
lesson_id_6 = 300 OR
lesson_id_7 = 300 OR
lesson_id_8 = 300 OR
lesson_id_9 = 300 OR
lesson_id_10 = 300
)
LIMIT 1
我知道它不漂亮,但这是我的MySQL声明。我试图找到它= 300的lesson_id_xx。我怎样才能磨练它以便它只返回单个lesson_id_xx而不是所有它们?
这就是它现在的回报:
array(10) {
["lesson_id_1"]=> string(3) "279"
["lesson_id_2"]=> string(3) "292"
["lesson_id_3"]=> string(3) "293"
["lesson_id_4"]=> string(3) "294"
["lesson_id_5"]=> string(3) "295"
["lesson_id_6"]=> string(3) "296"
["lesson_id_7"]=> string(3) "297"
["lesson_id_8"]=> string(3) "298"
["lesson_id_9"]=> string(3) "299"
["lesson_id_10"]=> string(3) "300"
}
我只想要这个:
array(10) {
["lesson_id_10"]=> string(3) "300"
}
答案 0 :(得分:2)
帮助不大,但您可以使用where
缩短in
条款:
SELECT
lesson_id_1, lesson_id_2, lesson_id_3, lesson_id_4, lesson_id_5,
lesson_id_6, lesson_id_7, lesson_id_8, lesson_id_9, lesson_id_10
FROM hub_attendance
WHERE
student_id='351' AND course_id = '102' AND
300 in (lesson_id_1, lesson_id_2, lesson_id_3, lesson_id_4, lesson_id_5,
lesson_id_6, lesson_id_7, lesson_id_8, lesson_id_9, lesson_id_10)
LIMIT 1
但是,我认为真正的答案是,如果你想更容易地查询它,你需要重新设计和规范化这个表。
答案 1 :(得分:1)
我认为你在谈论一个桌子(hub_attendance),你有很多lesson_id_xx列代表学生将要学习的课程,即学生可以选择的特定课程有不同的课程选项。这是正确的吗?如果是这样,缩短此陈述的正确方法是根据适当的关系原则重新设计表格,以便有两个表格:
hub_attendance:
id, student_id, course_id
attendance_lesson:
attendance_id, lesson_id
此attendance_lesson表是一个表示多对多关系的联接表,即一个课程可以有很多人参加,一个(课程)出勤可以有很多课程。
您的SQL将如下所示(假设您希望课程的所有出席人数均为300):
SELECT *
FROM hub_attendance
WHERE EXISTS(SELECT 1
FROM attendance_lesson
WHERE attendance_lesson.lesson_id = 300
AND attendance_lesson.attendance_id = hub_attendance.id)
答案 2 :(得分:0)
我认为你不能做你想做的事情......一旦你在Select
中添加了一些内容,就我所知,我无法回复:)
P.S:你应该真正重新设计你的数据库,不要让这个表格像这样......这是冒犯(并且会得罪)很多程序员......
答案 3 :(得分:0)
显然应该类似于
SELECT a.*,group_concat(lesson_id) FROM hub_attendance a, hub_lessons l
WHERE h.id=l.aid AND lesson_id = 300 GROUP BY aid