1

请看一下这个条件 mysql 查询:

SELECT attr1,attr2,attr3 FROM table 
WHERE 
( attr1 LIKE '%cond1%' OR attr1 LIKE '%cond2%' ) 
OR 
( attr2 BETWEEN '30' AND '45' ) 
OR 
( attr3 IN ('cond3') AND attr3 = 'cond4' AND attr3 BETWEEN '18' AND '30' ) 
ORDER BY CASE 
WHEN ( attr1 LIKE '%cond1%' OR attr1 LIKE '%cond2%' ) THEN 1 
WHEN ( attr2 BETWEEN '30' AND '45' ) THEN 2 
ELSE 3 
END

有没有办法用 mysql 和 php 获得每个条件返回的行数?还是处于租赁条件 3?

例如,我需要一种方法来知道条件 3 返回了 200 行并将此值存储到 php 变量中。

4

1 回答 1

1

您可以使用CASE WHEN ... THEN ... ELSE ... ENDwith SUM(或COUNT使用NULL作为ELSE结果)作为SELECT. 使用上面给出的示例,您将执行以下操作:

SELECT
    SUM(CASE WHEN attr1 LIKE '%cond1%' OR attr1 LIKE '%cond2%' THEN 1 ELSE 0 END) AS condition1count,
    SUM(CASE WHEN attr2 BETWEEN '30' AND '45' THEN 1 ELSE 0 END) AS condition2count,
    SUM(CASE WHEN attr3 IN ('cond3') AND attr3 = 'cond4' AND attr3 BETWEEN '18' AND '30' THEN 1 ELSE 0 END) AS condition3count
FROM
    table
...

但是请记住,根据数据的内容,某些行可能匹配 3 个条件中的多个条件,因此 3 个计数的总和可能大于返回的行数。

于 2013-03-02T18:40:55.600 回答