How to select a single record in a left join

前端 未结 8 1053
我寻月下人不归
我寻月下人不归 2021-02-01 02:40

I need to select a specific model from the Models table using its key ModelID. I also need to add a blurb of content from the Model_Content table. The Models_Content table, howe

8条回答
  •  无人共我
    2021-02-01 03:23

    This may be an expansion on Randy's answer, but it's not completely clear to me.

    For performance reasons I wanted to minimize the number of SELECT statements in my query, so I used a MIN statement within the primary select instead of within the JOIN:

    SELECT 
        table_1.id AS id, 
        table_1.name AS name,
        MIN(table_2.id) AS table_2_id 
    FROM table_1
    LEFT JOIN table_2 ON table_2.table_1_id = table_1.id
    -- additional JOINs and WHERE excluded
    GROUP BY table_1.id, table_1.name
    LIMIT 5
    

    There may be tradeoffs depending on the total amount of data. IDK. My query needs to tunnel into the data from a condition several steps removed.

提交回复
热议问题