一个查询中的变量WHERE

时间:2016-06-28 16:27:29

标签: php mysql

我正在尝试列出一个简单的查询。

我的表格users包含namepayment列(其值可以是10

我想要全部回复并计算有多少付款0和多少付款1。

我不知道put变量在哪里:"WHERE payment = 1 or 2"

$query=mysql_query('SELECT DISTINCT(COUNT(*)) AS how, name FROM users WHERE category = "1" group by name');

    while($result=mysql_fetch_array($query))
    {
        echo 'Company: '.$result['name'].' - payment0: ??? / payment1: ???<br>';
    }

示例:

name | payment

aaa 1

aaa 0

bbb 1

bbb 1

bbb 1

结果应该是:

Company: aaa - payment0: 1, payment1: 1

Company: bbb - payment0: 0, payment1: 3

在一个问题中如何做到这一点?

3 个答案:

答案 0 :(得分:0)

如果我理解正确,这是你的答案:

$query = mysql_query('SELECT DISTINCT(COUNT(*)) AS how, name FROM users WHERE category = "1" AND payment IN (1,2) GROUP BY name');

答案 1 :(得分:0)

由于您要汇总不同列中的不同行(不同列在payment0中计算,而不是在同一行的payment1中),您需要使用子查询:

SELECT DISTINCT 
    name, 
    q0.payment0 as payment0, 
    q1.payment1 as payment1 
FROM 
    users LEFT JOIN (
        SELECT DISTINCT name, COUNT(*) as payment0 
        FROM users WHERE category = 0 ) as q0 
        ON users.name = q0.name
    LEFT JOIN
        SELECT DISTINCT name, COUNT(*) as payment1 
        FROM usersWHERE category = 1 ) as q1 
        ON users.name = q1.name

然后抓取:

while($result=mysql_fetch_array($query))
{
    echo 'Company: '.$result['name'].' - payment0: ['payment0'] / payment1: ['payment1']<br>';
}

答案 2 :(得分:0)

您需要的查询是:

SELECT
    `name`,
    COUNT(IF(`payment` = 0, 1, 0)) AS `payment0`
    COUNT(IF(`payment` = 1, 1, 0)) AS `payment1`
FROM
    `users`
WHERE
    `category` = '1'
GROUP BY
    `name`