我知道有可能,但是我没有足够的经验来知道如何进行子查询。 情况如下:
Table 1: +--------------------+--------------------+ | v_id | v_name | +--------------------+--------------------+ | 1 | v_name1 | +--------------------+--------------------+ | etc... Table 2: +--------------------+--------------------+ | a_id | a_name | +--------------------+--------------------+ | 1 | a_name1 | +--------------------+--------------------+ | etc... Table 3: +--------------------+--------------------+ | v_id | a_id | +--------------------+--------------------+ | 1 | 1 | +--------------------+--------------------+ | 1 | 2 | +--------------------+--------------------+ | 1 | 3 | +--------------------+--------------------+ | 2 | 3 | +--------------------+--------------------+ | 2 | 1 | +--------------------+--------------------+
我相信这是很普遍的情况。 因此,我在Table 1和中都有唯一的条目Table 2。 我想SELECT从中Table 1获取所有行,并获取(作为每行中的最后一个单元格)具有相应值的行数Table 3。
Table 1
Table 2
SELECT
Table 3
这不起作用:
SELECT t1.* , COUNT(SELECT t3.* FROM `table_3` t3 WHERE t3.v_id = t1.v_id) as entries FROM `table 1` t1;
我敢肯定,这里的专家会告诉我这是完全错误的,但是坦率地说,这就是我想要的(还有一些有用的解决方案!)。;)
使用:
SELECT t1.*, COALESCE(x.num_rows, 0) AS entries FROM `table 1` t1 LEFT JOIN (SELECT t3.v_id, COUNT(*) 'num_rows' FROM `table_3` t3 GROUP BY t3.v_id) x ON x.v_id = t1.v_id