Mysql查询语法

时间:2012-04-09 15:14:21

标签: php mysql

我的查询有点问题。我需要选择任何可能的组合...... 我正在尝试通过查询在db中搜索

"SELECT * FROM `events` WHERE
                            `start_time` >= '{$current_time}' AND
                            `start_time` >=  '{$limit_from}' AND
                            `end_time` <= '{$limit_to}' AND
                            `filter_large` = '{$filter_large}'"
它给了我3个结果 第二个

"SELECT * FROM `events` WHERE
                            `start_time` >= '{$current_time}' AND
                            `start_time` >=  '{$limit_from}' AND
                            `end_time` <= '{$limit_to}' AND
                            `filter_education` = '{$filter_education}'"

给了我4个结果 但我想要像这样一起查询它们..

"SELECT * FROM `events` WHERE
                          (
                            `start_time` >= '{$current_time}' AND
                            `start_time` >=  '{$limit_from}' AND
                            `end_time` <= '{$limit_to}' AND
                            `filter_education` = '{$filter_education}'
                          ) OR (
                            `start_time` >= '{$current_time}' AND
                            `start_time` >=  '{$limit_from}' AND
                            `end_time` <= '{$limit_to}' AND
                            `filter_large` = '{$filter_large}'
                          )

它只给我4个结果而不是7个。我做错了什么?

4 个答案:

答案 0 :(得分:3)

尝试使用UNION operator

SELECT * FROM `events` WHERE
(
    `start_time` >= '{$current_time}' AND
    `start_time` >=  '{$limit_from}' AND
    `end_time` <= '{$limit_to}' AND
    `filter_education` = '{$filter_education}'
)

UNION

SELECT * FROM `events` WHERE
(
    `start_time` >= '{$current_time}' AND
    `start_time` >=  '{$limit_from}' AND
    `end_time` <= '{$limit_to}' AND
    `filter_large` = '{$filter_large}'
)

答案 1 :(得分:2)

  

给了我3个结果

     

第二个给了我4个结果

     

想要同时查询它们

     

它只给了我4个结果而不是7个

这可能是因为这两个查询共享三条记录。唯一的区别是你的最后一个条件,所以你可以将它们组合起来,保持其他条件不变:

SELECT * 
FROM `events` 
WHERE `start_time` >= '{$current_time}' 
AND `start_time` >=  '{$limit_from}' 
AND `end_time` <= '{$limit_to}' 
AND (`filter_large` = '{$filter_large}' OR `filter_education` = '{$filter_education}')

答案 2 :(得分:0)

我想你想要一个UNION:

"SELECT * FROM `events` WHERE
`start_time` >= '{$current_time}' AND
`start_time` >=  '{$limit_from}' AND
`end_time` <= '{$limit_to}' AND
`filter_large` = '{$filter_large}'
UNION
SELECT * FROM `events` WHERE
`start_time` >= '{$current_time}' AND
`start_time` >=  '{$limit_from}' AND
`end_time` <= '{$limit_to}' AND
`filter_education` = '{$filter_education}'"

答案 3 :(得分:0)

UNION用于将多个SELECT语句的结果合并到一个结果集中。

希望这有帮助:D