开发者

How to select the COUNT() of a joined table when the joined table has a combination of multiple columns as its primary key?

开发者 https://www.devze.com 2023-03-28 18:35 出处:网络
I am trying to jo开发者_如何学Cin two tables in sql and get the count of the second table. The second table has several columns, three of which together serve as the primary key. My query started as:

I am trying to jo开发者_如何学Cin two tables in sql and get the count of the second table. The second table has several columns, three of which together serve as the primary key. My query started as:

SELECT times.*, COUNT(paylog.*) AS `total` 
FROM times 
LEFT JOIN paylog 
ON paylog.type = 'work' 
AND paylog.targetID = times.id 

I get dinged for using the table name in the count() arguments:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '*) AS total FROM times LEFT JOIN paylog ' at line 1

If there was a single unique column in the paylog table, I could follow the advice given here: Can I count number of rows in joined table? But that is not the case. How can I select the count of all the joined rows on the paylog table? I need to have it be a join because it currently gets the count with a subquery and it makes it a little slow.


Count will only return the number of non null values in a column or the number of rows in a result set for the special case of count(*). In other words count(paylog.*) isn't valid SQL.

You don't need a unique column in the paylog table to do a valid count, any column will do. If the join is successful it'll increment the count, if not the column's value will be null and the count stays the same.

If you're trying to get the count of linked rows in paylog for each row in times then you'll also need a group by times.id clause.

0

精彩评论

暂无评论...
验证码 换一张
取 消