MySQL计算并使用来自另一个表的列表来列出事件

时间:2014-11-28 11:31:13

标签: mysql procedure sql-like

我有两张这样的表:

cars                            users
-------------------------      ---------------------------
| car    | description   |     | name   | car_owned      |
-------------------------      ---------------------------
| BMW    | Good Choice   |     | abcd   | BMW, nano      |
| Ferrari| better choice |     | efgh   | Ferrari, BMW   |
| nano   | with in budget|     | ijkl   | nano           |
--------------------------     | mnop   | nano           |
                               ---------------------------

我正在尝试创建一个程序:

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `car_count`()
BEGIN
SELECT `cars`.`car`, `users`.count(*) FROM `cars`, `users` WHERE `users`.`car_owned`
                       LIKE CONCAT('%',`cars`.`car` , '%') ;.
END $$
DELIMITER ;

我需要这样的东西:

----------------------
| car     | count(*) |
----------------------
| BMW     | 2        |
| Ferrari | 1        |
| nano    | 3        |
----------------------

2 个答案:

答案 0 :(得分:0)

DELIMITER $$
CREATE DEFINER=`root`@`localhost` PROCEDURE `car_count`()
BEGIN
SELECT `car`, count(*) FROM `cars` JOIN `users` ON FIND_IN_SET(car,REPLACE(car_owned,' ',''))>0
GROUP BY car
END $$
DELIMITER ;

答案 1 :(得分:0)

添加另一张表。怎么样:

users table
--------------   
| id  |  name
--------------
| 1   |  abc 
| 2   |  def
| 3   |  ghi


cars table                  
--------------------------------   
| id  |  name    | description   
--------------------------------
| 1   |  BMW     | Good Choice   
| 2   |  Ferrari | better choice 
| 3   |  nano    | with in budget


user_cars table
------------------
user_id  |  car_id
------------------
1        |   1
1        |   3
2        |   2
2        |   1
....

然后获得每辆车的用户数量

select c.name, count(u.id) as owned_count
from cars c
left join user_cars uc on uc.car_id = c.id
left join users u on uc.user_id = u.id
group by c.name