簡體   English   中英

使用SQL子查詢或JOIN子句進行選擇

[英]Selecting using SQL Subqueries or the JOIN Clause

所以我有這些表。

該表存儲點贊:

Table Name: Action

Id   Creator   Type   Target     <--- The `Target` here is the `Id` in Posts
1    1         like   1
2    2         like   1
3    3         like   1
4    1         like   2

該表存儲帖子:

Id   Creator
1    1
2    2

任何表中的列名Creator都是指Account表中的Id列(此處未顯示)。

我想選擇一個帳戶帖子獲得的喜歡總數。 我已經嘗試過下面的查詢,但是它給出了語法錯誤。

SELECT count(`Id`) AS Check FROM `Action` WHERE `Type`='like' AND `Target`= (SELECT `Id` FROM `Posts` WHERE `Creator` = '1');

我不確定在這里JOIN子句是否更合適。

通過將表和GROUP BY結合在一起並計算適當的目標,您將獲得總和。

SELECT
    p.creator,      
    COUNT(a.target) 
FROM
    posts p
INNER JOIN
    Action a
ON
    a.target = p.id
WHERE
    a.Type = 'like' AND p.creator = 1
GROUP BY
    p.creator;

這是SQL



    select a.ID,a.Creator,a.Type,a.Target, Count(p.*)Total
    from Action a 
    join posts p on a.Target=p.Creator
    where 
    a.Type='like'
    and a.Target=1;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM