簡體   English   中英

困惑於一個稍微復雜的LEFT / RIGHT JOIN查詢

[英]Confused on a somewhat complex LEFT/RIGHT JOIN query

感謝您抽時間閱讀。

基本上我有3張桌子。 帖子,關注者,藝術家。 我想做的是從用戶“關注”的“藝術家”中提取所有“帖子”。 我傳入了user_id,並嘗試從“帖子”和“藝術家”中提取數據

Posts /* the posts table */
id
body
artist_id
timecode

Follows /* the follows table */
id
artist_id
user_id

Artists /* the artists table */
id
name

因此,我的基本查詢如下所示:

SELECT Posts.id,Posts.body,Posts.timecode,Artists.id AS artist_id,Artists.name
FROM Posts,Artists
LEFT JOIN Artists
ON Posts.artist_id = Artists.id

現在這是我開始感到困惑的地方。 我猜想我需要在“關注”表上使用另一個JOIN語句,以便將返回結果限制為同時具有user_id和artist_id的“關注”條目的行。

即:

RIGHT JOIN Follows
ON Posts.artist_id = Follows.artist_id
WHERE Follows.user_id = :userid

我的問題是,盡管我覺得自己在正確的軌道上,但我什至不確定如何正確編寫此代碼……

任何幫助將非常感激!!! 謝謝。

編輯請注意,我正在從Posts和Artists表中提取數據,而不僅是Posts表。 不知道這是否有很大的不同。

我看不到您需要外部聯接,標准SQL內部聯接應返回所需的集合。 您必須信任SQL才能找到您感興趣的所有行。

SELECT
  p.*
FROM
  posts p,
  artists a,
  follows f
WHERE
  f.user_id = :userid AND
  a.id = f.artist_id AND
  p.artist_id = a.id
;
SELECT p.id,p.body,p.timecode,a.id AS artist_id,a.name
FROM Posts p
INNER JOIN Follows f ON p.artist_id = f.artist_id
INNER JOIN Artists a ON f.artist_id = a.id
WHERE f.user_id = X

還沒有檢查語法,我希望可以。

暫無
暫無

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

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