如何在同一查询中选择并获得COUNT?

时间:2019-02-14 20:11:27

标签: python mysql sql python-3.x

我有一个这样组装的查询(使用Django后端):

sql = 'SELECT * FROM `table` WHERE'
if condition1:
    sql += ' `col1` = "foo" OR'

if condition2:
    sql += ' `col2` = "bar" OR'
...

if conditionN:
    sql += ' `colN` = "foobar" OR'

sql = sql[:-2] //to remove the extra 'OR'

sql += 'ORDER BY `col1` LIMIT x OFFSET y'

print(sql) //'SELECT * FROM `table` WHERE `col1` = "foo" OR `col2` = "bar" ... OR `colN` == "foobar" ORDER BY `col1` LIMIT x OFFSET y'
  

我需要一个查询来获取COUNT(*)所有行的table,但仍然需要从数据库中获取SELECT的条件和{{1} }

我试图做这样的事情:

LIMIT

如果您还不能确定的话,那么我对上面查询中发生的事情完全感到困惑,这是行不通的(显然)。

更新

该表如下所示:

SELECT t1.*, IFNULL(COUNT(t2.*), 0) AS childCount 
FROM `table` AS t1 LEFT JOIN `table` AS t2
WHERE `col1` = "foo" OR `col2` = 'bar' OR `colN` = 'foobar' 
ORDER BY `col1` desc LIMIT 10;

我需要的示例查询:

+--------+----------+
|  col1  |   col2   | 
+--------+----------+
|   a    |   foo    |      
|   b    |   foo    |      
|   c    |   bar    |      
|   d    |   bar    |     
|   e    |   foo    | 
+--------+----------+

它需要返回此值:

'SELECT *, COUNT(*) as childCount FROM `table` WHERE `col2` = "foo" LIMIT 1 OFFSET 0'

建议/说明将不胜感激:)

2 个答案:

答案 0 :(得分:0)

根据您更新的问题

可以

select col1,col2,count from (
select col2,count(col2) as count from table1 group by col2 order by col1)a
order by col1
limit 1
offset 0

答案 1 :(得分:0)

IIUC

SELECT a.col1, a.col2, b.childCount
FROM table a
JOIN (
  SELECT c.col2, COUNT(1)
  FROM table c
  GROUP BY 1
  ORDER BY 2 DESC) b
ON a.col2 = b.col2
LIMIT 1
OFFSET 0