计算组连续行中的状态数

时间:2015-12-27 14:24:50

标签: php mysql sql

我接管了一个真正混乱的项目,所以我离开了糟糕的代码结构,迫使我基本上编程SQL。所以改变计算方法现在不是一种选择。

我有$sqlAdd变量需要在函数中填充,然后将其连接到主查询以计算丢失票证的数量。

主要查询如下所示:

$sql = "SELECT COUNT(*) as num_tickets, SUM(t.total_amount) as total_payin, SUM(t.total_payout) as total_payout
FROM t WHERE t.tickettime BETWEEN '$dateFrom' AND '$dateTo' AND t.bsid = $bsID
$sqlAdd";

所以$ sqlAdd来自另一个函数

$sqlAdd = getSqlAdd();

在这个功能中我有这个:

$sqlAdd = " AND 'WON' NOT IN (
           SELECT GROUP_CONCAT(tr.ticketstatus)
           FROM tr INNER JOIN m ON tr.ticketid = m.ticketid
           WHERE tr.ticketid = t.ticketid GROUP BY m.ticket_groupid
           )
       AND 'PAYEDOUT' NOT IN (
           SELECT GROUP_CONCAT(tr.ticketstatus)
           FROM tr INNER JOIN m ON tr.ticketid = m.ticketid
           WHERE tr.ticketid = t.ticketid GROUP BY m.ticket_groupid
           )
       AND 'CLOSED' NOT IN (
           SELECT GROUP_CONCAT(tr.ticketstatus)
           FROM tr INNER JOIN m ON tr.ticketid = m.ticketid
           WHERE tr.ticketid = t.ticketid GROUP BY m.ticket_groupid
           )
       AND 'OPEN' NOT IN (
           SELECT GROUP_CONCAT(tr.ticketstatus)
           FROM tr INNER JOIN m ON tr.ticketid = m.ticketid
           WHERE tr.ticketid = t.ticketid GROUP BY m.ticket_groupid
           )";
当我执行它时,

GROUP_CONCAT(tr.ticketstatus)给我这些行

CLOSED,CLOSED,CLOSED
PAYEDOUT,PAYEDOUT
CLOSED,CLOSED
WON,LOST
LOST,WON,WON,WON,WON,WON
CLOSED,CLOSED
LOST,LOST,WON
WON,WON,WON,LOST,LOST,WON,WON
LOST

我只想计算其中只有LOST状态的行。所以结果应该是1.但我一直得到7.它计算结果中的每个LOST状态。

2 个答案:

答案 0 :(得分:0)

你似乎想要这样的东西:

SELECT COUNT(*) as num_tickets, SUM(t.total_amount) as total_payin,
       SUM(t.total_payout) as total_payout
FROM t
WHERE t.tickettime BETWEEN '$dateFrom' AND
      '$dateTo' AND t.bsid = $bsID AND
      NOT EXISTS (SELECT 1
                  FROM tr NATURAL JOIN
                       m NATURAL JOIN
                       tg
                  WHERE tr.ticketid = t.ticketid AND
                        tr.ticketstatus IN ('WON', 'PAYEDOUT', 'CLOSED', 'OPEN')
                 );

一些注意事项:

  • GROUP_CONCAT()不适合此类比较。在SQL中,您不会将列表转换为字符串,然后进行比较 - 至少在您需要性能的情况下。
  • 您应该避免NATURAL JOIN。对任何表的小改动都可以完全改变查询的语义。此外,还不清楚JOIN键是什么。我建议改为USING
  • 您可能希望子查询中有tr.ticketstatus NOT IN ('LOST')

答案 1 :(得分:0)

所以我写了非常丑陋的查询,这可能很慢,但是我正在努力获得我需要的结果。

import mechanize
username = "<username>"
password = "<password>"

ua = 'Mozilla/5.0 (X11; Linux x86_64; rv:18.0) Gecko/20100101 Firefox/18.0 (compatible;)'

br = mechanize.Browser()
br.set_handle_robots(False)
br.addheaders = [('User-Agent', ua), ('Accept', '*/*')]

br.open("https://www.instagram.com/accounts/login/")
br.select_form(nr=0)
br[username] = username
br[password] = password
result = br.submit().read()
f = open('output.html','w')
f.write(result)
f.close()