简体   繁体   English

MySQL左连接与另一个带有传递变量的表

[英]Mysql left join with another table with passed variable

I have 2 tables named projects and tracklines Every project can have multiple tracklines. 我有2个表分别命名为projectstracklines每个项目可以有多个跟踪线。

I have an SQL statement that will loop through my projects, but I want to be able to JOIN the trackline table with only 1 row. 我有一条将遍历我的项目的SQL语句,但我希望能够仅用1行加入跟踪线表。 What I want to do is get all tracklines that are part of a project, order them based on more than one field and do a LIMIT 1 on it so that I have one trackline which I'm joining with my project. 我要做的是获取项目中所有的跟踪线,基于多个字段对它们进行排序,并对其进行LIMIT 1,这样我就有一条要加入到我的项目中的跟踪线。

This is what I have so far: 这是我到目前为止的内容:

SELECT Project.* FROM `project` AS `Project`
LEFT JOIN (
    SELECT *
    FROM `trackline`
    WHERE `trk_deleted` = '0'
    ORDER BY `trk_state`, `trk_status`
    LIMIT 1
) t ON t.`trk_project` = `prj_id`
ORDER BY `prj_name`

The problem is that I am not getting the trk_state and trk_status values in my outer query. 问题是我在外部查询中没有得到trk_statetrk_status值。

I was thinking that my subquery could have WHERE trk_project = prd_id but I am not sure how to get that to happen. 我当时在想我的子查询可能有WHERE trk_project = prd_id但是我不确定如何使这种情况发生。

You need to pull values from that derived table as well: 您还需要从该派生表中提取值:

SELECT Project.*, t.*
FROM ...

right now it's retrieving ONLY the fields from the Project table. 现在,它仅从Project表中检索字段。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM