mysql查询,可以用来代替mysql_num_rows

时间:2010-11-10 07:40:44

标签: php mysql

我想知道如何编写一个mysql查询来检查其他表中存在多少条记录?

table 1 : names

id name
-- ----
4  john
5  mike
6  jenny

table 2 : cars

id name_id car
-- ------- ---
1   4      bmw
2   4      wv
3   6      honda

query = "SELECT * FROM names WHERE id = '4'"< - 在该查询中我还想检查汽车表中有多少记录或者是否有记录?

3 个答案:

答案 0 :(得分:3)

这应该这样做:

SELECT names.id, name, COUNT(car) as 'cars'
FROM names LEFT JOIN cars ON names.id = cars.nameid 
WHERE names.id = '4'
GROUP BY names.id, name

答案 1 :(得分:1)

在另外LEFT OUTER JOIN

中为每个人添加汽车数量
SELECT  n.*, c.cnt
FROM    names n
        LEFT OUTER JOIN (
          SELECT  name_id, cnt = COUNT(*)
          FROM    cars
          GROUP BY
                  name_id
        ) c ON c.name_id = n.id
WHERE   ID = 4

如果性能有问题,您可以将条件添加到左连接中,但代价是可维护性。

SELECT  n.*, c.cnt
FROM    names n
        LEFT OUTER JOIN (
          SELECT  name_id, cnt = COUNT(*)
          FROM    cars
          WHERE   name_id = 4 -- Condition needs to be updated in two places
          GROUP BY
                  name_id
        ) c ON c.name_id = n.id
WHERE   ID = 4

答案 2 :(得分:1)

SELECT n.*, COUNT(c.*) FROM names n, cars c WHERE n.id = 4

您也可以为该列命名:

SELECT n.*, COUNT(c.*) AS `num_cars` FROM names n, cars c WHERE n.id = 4