6

这是MySQL:

SELECT  a.id,
        a.name,
        a.n,
        a.r,
        a.pot,
        a.ticket_price,
        a.starting_tickets,
        a.started,
        a.end,
        COUNT(b.id) tickets_bought 
FROM current_lotteries a
   JOIN lottery_tickets b ON b.lid=a.id
WHERE a.cid=1 
ORDER BY started DESC LIMIT 1    

在搜索中,如果没有行 froma但有行 in b(即COUNT(b.id)is not NULL),则此查询返回一行,其中NULL包含a字段值以及COUNT(b.id)as的值tickets_boughtnum_rows = 0如果表中没有结果,如何修改此查询使其不返回行 ( ) a

一个快照。

询问

4

2 回答 2

9

如果没有子句,MySQL(它允许在其他 RDBMS 中出现错误的情况下这样做)在应该对它们进行分组时GROUP BY将聚合组应用于所有行。b添加GROUP BY a.id

SELECT  a.id,
        a.name,
        a.n,
        a.r,
        a.pot,
        a.ticket_price,
        a.starting_tickets,
        a.started,
        a.end,
        COUNT(b.id) tickets_bought 
FROM current_lotteries a
   JOIN lottery_tickets b ON b.lid=a.id
WHERE a.cid=1 
GROUP BY a.id
ORDER BY started DESC LIMIT 1    

以上将适用于 MySQL,但不适用于其他地方。更便携的版本使用相关子查询:

SELECT  a.id,
        a.name,
        a.n,
        a.r,
        a.pot,
        a.ticket_price,
        a.starting_tickets,
        a.started,
        a.end,
        b.tickets_bought
FROM current_lotteries a
        /* More portable to join against a subquery which returns the count per group */
        JOIN (
            SELECT b.lid, COUNT(*) AS tickets_bought 
            FROM lottery_tickets 
            GROUP BY lid
        ) b ON a.id = b.lid
WHERE a.cid = 1
ORDER BY started DESC LIMIT 1
于 2013-01-06T13:44:13.503 回答
1

试试这个:

SELECT a.id, a.name, a.n, a.r, a.pot, a.ticket_price, 
       a.starting_tickets, a.started, a.end, b.tickets_bought 
FROM current_lotteries a 
RIGHT JOIN (SELECT b.lid, COUNT(*) AS tickets_bought 
            FROM lottery_tickets GROUP BY lid ) b ON a.id = b.lid 
WHERE a.cid = 1 
ORDER BY started DESC 
LIMIT 1;
于 2013-01-06T13:55:34.890 回答