重写搜索查询

时间:2012-11-14 05:58:33

标签: mysql

我的准系统搜索系统变得更加复杂,并且有很多奇怪的问题。如何重写此搜索查询以更加准确和有效

tbl_notes表只有course的id,但要将其添加到搜索中,我使用内部查询来检查它。这有很多问题,我在mysql中不太强大,任何帮助都会受到赞赏。

TBL_NOTES:

[id][user_id][note_title][note_title][topic][course][note]

TBL_COURSES:

  [id][user_id][course_name]

   SELECT * FROM `tbl_notes` 
    WHERE `active` = '0' 
    AND `valid_note` = '0' 
    AND `user_id` = '33' 
    AND `note` LIKE '%biology%' 
    OR `topic` LIKE '%biology%' 
    OR `note_title` LIKE '%biology%' 
    OR `course` IN (SELECT `id` FROM tbl_courses WHERE `course_name` LIKE '%biology%' AND user_id = '33') 
    ORDER BY id DESC LIMIT 0, 6

由于

2 个答案:

答案 0 :(得分:2)

我会这样写:

SELECT
  DISTINCT n.*
FROM
  `tbl_notes` n left join `tbl_courses` c
  on n.course = c.id
WHERE
  n.`user_id` = '33'
  AND n.`active` = '0' 
  AND n.`valid_note` = '0'
  AND (n.`note` LIKE '%biology%' 
       OR n.`topic` LIKE '%biology%' 
       OR n.`note_title` LIKE '%biology%' 
       OR c.`course_name` LIKE '%biology%') 
ORDER BY n.id DESC LIMIT 0, 6

答案 1 :(得分:1)

也许?:

  SELECT * FROM `tbl_notes` 
    WHERE `active` = '0' 
    AND `valid_note` = '0' 
    AND `user_id` = '33' 
    AND 
   (`note` LIKE '%biology%' 
    OR `topic` LIKE '%biology%' 
    OR `note_title` LIKE '%biology%' 
    OR `course` IN (SELECT `id` FROM tbl_courses WHERE `course_name` LIKE '%biology%' AND user_id = '33') 
    )
    ORDER BY id DESC LIMIT 0, 6