在两个表之间执行JOIN

时间:2014-12-30 12:45:13

标签: mysql sql select count group-by

我有两张这样的表:

TABLE_1

id   user_id   item_id   item_number
15      1         1        7   
16      1         2        12
17      1         3        1
18      1         4        0
19      1         5        11
20      5         1        2   
21      5         2        2
22      5         3        5
23      5         4        7
24      5         5        1

TABLE_2

id   user_id   item_id   attribute
41      5         1        1   
42      1         1        1
43      7         5        1
44      1         4        1
45      1         4        0

我想从table_1中选择user_id,item_id和item_number,并从table_2中选择table_1.user_id = table_2.user_id和table_1.item_id = table_2.item_id的行数。

我有这个:

SELECT item_id, item_number, COUNT(attribute) AS number
FROM table_1
LEFT OUTER JOIN table_2 ON table_1.user_id = table_2.user_id
WHERE table_1.user_id='1'

你能帮助我吗?

预期结果:

user_id   item_id   item_number number
   1         1         7          1   
   1         2         12         0
   1         3         1          0
   1         4         0          2
   1         5         11         0

3 个答案:

答案 0 :(得分:1)

试试这个:

SELECT t1.user_id, t1.item_id, t1.item_number, COUNT(attribute) AS number
FROM table_1 t1
LEFT OUTER JOIN table_2 t2 ON t1.user_id = t2.user_id AND t1.item_id = t2.item_id
WHERE t1.user_id = '1'
GROUP BY t1.user_id, t1.item_id;

答案 1 :(得分:0)

你必须使用别名,因为相同的列名混淆了服务器以确定哪个列必须获取..所以你可以使用它..

SELECT t1.user_id,t1.item_id, t1.item_number, COUNT(attribute) AS number
FROM table_1 t1
LEFT OUTER JOIN table_2 t2 ON t1.user_id = t2.user_id
WHERE t1.user_id='1' GROUP BY t1.user_id, t1.item_id;

答案 2 :(得分:0)

由于您实际上不需要table_2中的任何列值,因此我会使用子查询来获取计数:

select user_id, item_id, item_number,
       (select count(*) from table_2
        where table_1.user_id = table_2.user_id
          and table_1.item_id = table_2.item_id)
from table_1
WHERE table_1.user_id='1'