我有兩個表:MySQL的:LEFT JOIN表ON table.id IN()
訂單
+----+------+-------+
| id | name | notes |
+----+------+-------+
| 1 | Adam | 1,2 |
| 2 | Ema | 3 |
| 3 | Petr | 1,3 |
+----+------+-------+
注意
+----+---------------------+
| id | text |
+----+---------------------+
| 1 | This is first note |
| 2 | This is second note |
| 3 | And third note |
+----+---------------------+
我需要選擇行來自訂單和組concat基於Orders.notes的第二個表中的文本。
如果我用這個語句如預期This is first note;This is second note
但
SELECT o.name, o.notes
,GROUP_CONCAT(DISTINCT n.text SEPARATOR ';') AS notes_text
FROM orders o
LEFT JOIN notes n ON n.id IN (1,2)
WHERE o.id = 1;
的結果,如果我用這個說法,我需要,其中notes.id IN(orders.notes)
SELECT o.name, o.notes
,GROUP_CONCAT(DISTINCT n.text SEPARATOR ';') AS notes_text
FROM orders o
LEFT JOIN notes n ON n.id IN (o.notes)
WHERE o.id = 1
它只返回第一個文本This is first note
。爲什麼?
你只是問'爲什麼'或者你需要另一個想要的結果? – RubahMalam
我需要使用第二條語句,但期望得到類似於第一條語句的結果。 – hovado
'orders.notes'是這個問題的一個不可擴展的解決方案。你應該把'order_id'放到你的'notes'表中,那麼SQL就會更有意義。 –