我想从 table1 中显示一些数据用户,并计算该用户从 table2 创建的所有网址。
例如我有这样的数据:
表1
id username email join_date
123 user123 123@email.com 12-11-2018
456 user456 456@email.com 13-11-2018
789 user789 789@email.com 14-11-2018
表2
id username url date_insert
321 user789 url1 12-12-2018
654 user456 url2 13-12-2018
987 user789 url3 14-12-2018
312 user789 url4 14-12-2018
这是我的代码,但当然是错误。
SELECT * COUNT(url.table2)
FROM table1, table2
WHERE table1.username = table2.username
ORDER BY table1.join_date DESC
我想显示这样的数据
最终结果必须像这样
id(table1) email(table1) join_date(table1) count(url)
---------- -------------- ----------------- -------------
123 789@email.com 14-11-2018 3
456 456@email.com 13-11-2018 1
789 123@email.com 12-11-2018 0
答案 0 :(得分:1)
SELECT table1.*, count(table2.url)
FROM `table1`
join table2
ON table2.username=table1.username
Group By table2.username
我建议您使用整数作为外键引用。
答案 1 :(得分:0)
您可以尝试以下查询: -
SELECT table1.id,
table1.username,
table1.email,
table1.join_date,
COUNT(table2.id) AS url
FROM table1
LEFT JOIN table2
ON table2.username = table1.username
GROUP BY table1.username
ORDER BY join_date DESC