2014-10-17 41 views
1

加入我有這樣的查詢如何選擇,其中左在MySQL

SELECT tb_post.*, 
     (SELECT GROUP_CONCAT(DISTINCT tb_category.category_name) 
     FROM tb_category 
     LEFT JOIN tb_terms ON tb_terms.parent_1 = tb_category.category_id 
     WHERE tb_terms.post_id = `tb_post`.post_id and category_type="post" 
     GROUP BY tb_terms.post_id) AS parent1 
FROM (`tb_post`) 

enter image description here

但這其中不運行。這總是返回表中的所有行..我想添加在哪裏爲什麼?

我不想改變形狀查詢和我我需要tb_post所有的數據,但其中tb_category.category_type = $值,不更改查詢

+0

無關的你的主要問題,但你的子查詢使用LEFT OUTER JOIN,而且還檢查WHERE子句中左連接表中列的值。至於任何非匹配列將有一個NULL值,它不可能匹配tb_post.post_id(它看起來像一個唯一的ID)。因此,它將它呈現爲有效的INNER JOIN。 – Kickstart 2014-10-17 10:38:04

回答

1

的結構如果u不需要tb_post *然後刪除,因爲它從調用數據庫中,如果所有的數據內層查詢獲得較少的記錄,那麼tb.post那麼它也顯示最高紀錄(tb_post)

+0

我需要tb_post的所有數據,但tb_category.category_type ='$ value' – 2014-10-17 06:59:13

+0

在tb_term和category表中有任何常見字段? – Affan 2014-10-17 07:01:06

+0

是的,tb_terms.parent_1是加入tb_category .... 這個參考http://www.grocerycrud.com/documentation/options_functions/set_relation_n_n – 2014-10-17 07:03:42

0

使用INNER JOIN:

SELECT tb_post.*, tc.categories 
FROM tb_post 
INNER JOIN (
    SELECT tb_terms.post_id, GROUP_CONCAT(DISTINCT tb_category.category_name) AS categories 
    FROM tb_category 
    LEFT JOIN tb_terms ON tb_terms.parent_1 = tb_category.category_id 
    WHERE tb_category.category_type="post" 
    GROUP BY tb_terms.post_id 
) tc ON tc.post_id = tb_post.post_id 
+0

hy Rimas。謝謝你,這是非常有用的,但我有另一個問題如何把你的查詢功能 - > http://notepad.cc/share/ghmy0Ko78c – 2014-10-17 07:54:00

+0

你的問題還不清楚。最簡單的方法就是返回這個查詢:'protected function relation_n_n_queries($ select){return「SELECT tb_post。* ...和查詢的其餘部分...」; }' – Rimas 2014-10-17 08:55:49

+0

Rimas非常感謝你。但是由你編碼並且由@Kickstart合併非常好 – 2014-10-17 20:06:38

0

最好SOLU重刑將是修改您的查詢@Rimas建議,但與生成該查詢的功能的片段,我看不到足以看到如何做到這一點。

如果這是不可能的,那麼我會被誘惑有點濫用HAVING子句和做這樣的事情: -

SELECT tb_post.*, 
     (SELECT GROUP_CONCAT(DISTINCT tb_category.category_name) 
     FROM tb_category 
     INNER JOIN tb_terms ON tb_terms.parent_1 = tb_category.category_id 
     WHERE tb_terms.post_id = `tb_post`.post_id 
     AND category_type="post" 
     GROUP BY tb_terms.post_id) AS parent1 
FROM (`tb_post`) 
HAVING parent1 IS NOT NULL 
+0

好。它真的幫助了我。非常感謝你 。你拯救了我的生命^ _ ^ – 2014-10-17 20:05:46