MySQL - 仅当左表中存在行时才加入

时间:2013-01-06 13:31:28

标签: mysql select join group-by

这是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    

在搜索中,如果a中没有行,但b中有行(即COUNT(b.id)不是NULL),则此查询返回一行NULL字段的值a以及COUNT(b.id)的{​​{1}}值tickets_bought。如果表num_rows = 0中没有结果,如何修改此查询以使其不返回行a

Snap。

query

2 个答案:

答案 0 :(得分:8)

如果没有GROUP BY子句,MySQL(允许在其他RDBMS中出错的情况)将聚合组应用于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

答案 1 :(得分: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;