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 ...
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大