dousikuai5417 2016-04-30 10:41 采纳率: 0%
浏览 362
已采纳

MYSQL'IN'和'COUNT'问题

I Have 2 SQL queries that I might not use correct:

SELECT 
    `contract_id`,
    `contract_title`,
    `contract_description`,
    `contract_postalcode`,
FROM
    `gmw_contracts` 
WHERE contract_title COLLATE UTF8_GENERAL_CI REGEXP "test" 
    OR contract_description COLLATE UTF8_GENERAL_CI REGEXP "test" 
    AND contract_postalcode IN (
        53111,53113,53129,53175,53225,53227,53229,53757
    ) ;

SELECT 
    COUNT(`contract_postalcode`) 
FROM
    `gmw_contracts` 
WHERE `contract_title` COLLATE UTF8_GENERAL_CI REGEXP "test" 
    OR `contract_description` COLLATE UTF8_GENERAL_CI REGEXP "test" 
    AND `contract_postalcode` IN (
        53111,53113,53129,53175,53225,53227,53229,53757
    ) ;

The first query selects rows with given parameters like keyword and postalcode etc, but i don't get the desired result. Seems like the postalcode thing is completely ignored.

The second query should count it so i can paginate the result in PHP (BUT I don't want to count PHP)

THE SOLUTION for the first query: I can use HAVING instead of AND. But I need to do it with the counting query too. COUNT and HAVING dont work together in this exapmle.

U got any hints or solutions for me?

  • 写回答

1条回答 默认 最新

  • douyou4819 2016-04-30 10:46
    关注

    Your first problem is caused by the combination of OR and AND:

    ... WHERE ... OR ... AND ...
    

    Here the AND clause will probably not do what you want / expect as the conditions return true if any of the OR conditions is met.

    You probably want:

    ... WHERE (... OR ...) AND ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 给自己本科IT专业毕业的妹m找个实习工作
  • ¥15 用友U8:向一个无法连接的网络尝试了一个套接字操作,如何解决?
  • ¥30 我的代码按理说完成了模型的搭建、训练、验证测试等工作(标签-网络|关键词-变化检测)
  • ¥50 mac mini外接显示器 画质字体模糊
  • ¥15 TLS1.2协议通信解密
  • ¥40 图书信息管理系统程序编写
  • ¥20 Qcustomplot缩小曲线形状问题
  • ¥15 企业资源规划ERP沙盘模拟
  • ¥15 树莓派控制机械臂传输命令报错,显示摄像头不存在
  • ¥15 前端echarts坐标轴问题