0

This works before I put the CONCAT statement in. I was hoping to return a tuple for the uploads field based off of the subquery.

def my_query():
    conn = create_connection() 
    cur = conn[0]
    cur.execute("""SELECT d.id, s.val1, d.val2, s.val3, d.val4,
                          r.val5, r.val6, r.val7,
                          CONCAT(SELECT u.id, u.file_name, u.file_path FROM related_docs u WHERE u.icd_id = d.id)
                          AS uploads
                   FROM icd_d d, icd_s s, icd_r r
                   WHERE d.id = s.icd_id
                   AND d.id = r.icd_id
                   ORDER BY id ASC
                """)
    data = cur.fetchall()    
    return data
3
  • 1
    Is it a typo to have two ( after CONCAT? Commented Jan 9, 2020 at 18:30
  • I fixed the typo but still not working Commented Jan 9, 2020 at 18:33
  • Does the STRUCTURE GUARANTEE that the subquery returns not more than ONE record? Commented Jan 9, 2020 at 18:36

1 Answer 1

2

I think you want this:

(SELECT CONCAT(u.id, u.file_name, u.file_path) FROM related_docs u WHERE u.icd_id = d.id) AS uploads

but it is better to add spaces between each value:

(SELECT CONCAT(u.id, ' ', u.file_name, ' ', u.file_path) FROM related_docs u WHERE u.icd_id = d.id) AS uploads

This will work only if the subquery returns only 1 row.
If there is a case of multiple rows, use GROUP_CONCAT() also to get a comma separated list of each row:

(SELECT GROUP_CONCAT(CONCAT(u.id, ' ', u.file_name, ' ', u.file_path)) FROM related_docs u WHERE u.icd_id = d.id) AS uploads
Sign up to request clarification or add additional context in comments.

4 Comments

I do need multiple rows
@MikeC. It is impossible to return "multiple rows" in one field of single record. Either concatenate everything into one long string, or JOIN instead of correlated subquery.
@MikeC. see in my edited answer a solution to get the results as a comma separated list.
@forpas Perfect. Thanks.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.