我正在寻找一些建议来组合来自不同表的两个COUNT的总和的最佳方法,使用每个表中没有共同字段名称的字段。
目前我有两个单独的查询,可以计算外观和替换,如下所示。
SELECT
P.PlayerID AS id, COUNT(A.AppearancePlayerID) AS apps
FROM
sports_seasons S
LEFT OUTER JOIN sports_players P ON P.PlayerID = S.SeasonPlayerID AND S.SeasonID = '$seasonid'
LEFT OUTER JOIN sports_appearances A ON A.AppearancePlayerID = S.SeasonPlayerID AND A.AppearanceSeasonID = '$seasonid'
WHERE
P.PlayerID != ''
GROUP BY id
ORDER BY id
SELECT
P.PlayerID AS id, COUNT(SU.SubstitutionPlayerIDIn) AS subapps
FROM
sports_seasons S
LEFT OUTER JOIN sports_players P ON P.PlayerID = S.SeasonPlayerID AND S.SeasonID = '$seasonid'
LEFT OUTER JOIN sports_substitutions SU ON SU.SubstitutionPlayerIDIn = S.SeasonPlayerID AND SU.SubstitutionSeasonID = '$seasonid'
WHERE
P.PlayerID != ''
GROUP BY id
ORDER BY id
我目前的尝试如下:
SELECT P.PlayerID AS id,
(
SELECT
COUNT(A.AppearancePlayerID) AS apps
FROM
sports_seasons S
LEFT OUTER JOIN sports_players P ON P.PlayerID = S.SeasonPlayerID AND S.SeasonID = '$seasonid'
LEFT OUTER JOIN sports_appearances A ON A.AppearancePlayerID = S.SeasonPlayerID AND A.AppearanceSeasonID = '$seasonid'
WHERE
P.PlayerID != '' AND P.PlayerPublish != 0
)
+
(
SELECT
COUNT(SU.SubstitutionPlayerIDIn) AS subapps
FROM
sports_seasons S
LEFT OUTER JOIN sports_players P ON P.PlayerID = S.SeasonPlayerID AND S.SeasonID = '$seasonid'
LEFT OUTER JOIN sports_substitutions SU ON SU.SubstitutionPlayerIDIn = S.SeasonPlayerID AND SU.SubstitutionSeasonID = '$seasonid'
WHERE
P.PlayerID != '' AND P.PlayerPublish != 0
) AS total
FROM sports_players P
GROUP BY id
ORDER BY id
可悲的是,我没有在哪里。
以下是正在使用的表格。 DB是运动队球员出场记录。
PlayerID | PlayerName // Players table
AppearanceID | AppearancePlayerID | AppearanceSeasonID // A table collating first team appearance made
SubstitutionID | SubstitutionPlayerIDIn | SubstitutionSeasonID // A table collating substitution appearances made
SeasonID | SeasonPlayerID // A table handling registrations
使用MySQL 5.6。
答案 0 :(得分:1)
您可以使用它们作为派生表将两个查询的结果连接起来。我认为INNER JOIN就足够了。
<?xml version="1.0" encoding="utf-8"?>
<TabbedPage xmlns="http://xamarin.com/schemas/2014/forms"
xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
xmlns:prism="clr-namespace:Prism.Mvvm;assembly=Prism.Forms"
xmlns:local="clr-namespace:com.XXXXXXX"
prism:ViewModelLocator.AutowireViewModel="True"
BackgroundColor="White"
x:Class="com.XXXXXXXXXX.EditChargePage"
Title="{Binding Title}">
<local:EditChargeDetailsPage Title="Details" />
<local:EditChargeTrackingPage Title="Tracking" IsVisible="{Binding TabContext.HasTracking}" IsEnabled="{Binding TabContext.HasTracking}"/>
<local:EditChargeNotesPage Title="Notes" />
</TabbedPage>