简体   繁体   English

合并表/联接查询MySql

[英]Combine Tables / Join Query MySql

I am stuck with this query and I am not able to solve it. 我对此查询感到困惑,无法解决它。 I need help in joining tables. 我在连接表时需要帮助。

I have 4 tables (customer, product, status and offer). 我有4个表格(客户,产品,状态和报价)。

I want to read from these tables based on customer ID. 我想根据客户ID从这些表中读取。

In first 3 tables, the number of record against customer ID is one, but offer table may have more than one rows for a customer. 在前3个表中,针对客户ID的记录数为1,但是要约表对于客户而言可能有多于一行。

I want to read the latest row from the offer table for each customer. 我想从报价表中为每个客户阅读最新行。 I am not able make a query for this situation. 我无法查询这种情况。

For example 例如

Customer have columns (cID, Name, Surname)
STATUS (sID, cID, Status, Sdate)
ADDRESS (adID, cID, Addetail)
Offer (ID, cID, offer, offDate)

Here is my query, which is not working: 这是我的查询,不起作用:

SELECT c.ID, 
c.NAME, 
c.SURNAME, 
st.ID, 
st.Status, 
st.Sdate
ad.Addetial,
off.OffDATE
FROM customer c, address ad, status st, offer of

WHERE 
c.ID=ad.cID 
AND c.ID=st.cID 
AND c.ID = off.cID
.. 

I am confuse how to restrict the selection to one row from the offer table. 我很困惑如何将选择范围限制为要约表中的一行。 because if I put c.ID = off.cID then it will return all the offers which I don't want. 因为如果我输入c.ID = off.cID,那么它将返回我不需要的所有报价。

PS: I know there are similar questions, but I couldn't map it according to my situation. PS:我知道也有类似的问题,但是我无法根据自己的情况进行映射。 Using Max, returns only one row (even if there are many customers). 使用Max,仅返回一行(即使有很多客户)。

Try this one 试试这个

SELECT c.ID, 
c.NAME, 
c.SURNAME, 
st.ID, 
st.Status, 
st.Sdate
ad.Addetial,
off.OffDATE
FROM customer c   
WHERE 
INNER JOIN  address ad ON c.ID=ad.cID 
INNER JOIN  status st  ON AND c.ID=st.cID 
INNER JOIN (SELECT *,MAX(id) AS `max` FROM offer GROUP BY  id ,cID) off
ON c.ID = off.cID

I have used a subquery (SELECT *,MAX(id) AS max FROM offer GROUP BY id ,cID) to get the latest customer offers subquery will execute only once to get the desired latest dataset 我已使用子查询(SELECT *,MAX(id) AS max FROM offer GROUP BY id ,cID)来获取最新的客户要约子查询将仅执行一次以获取所需的最新数据集

You want the groupwise maximum , which can be obtained by joining the offer table to a grouped version of itself: 您需要成组的最大值 ,可以通过将offer表连接到自身的分组版本来获得:

SELECT c.ID,
       c.NAME, 
       c.SURNAME, 
       st.ID, 
       st.Status, 
       st.Sdate
       ad.Addetial,
       off.OffDATE
FROM   customer c
  JOIN address  ad ON ad.cID = c.ID
  JOIN status   st ON st.cID = c.ID
  JOIN (offer  off NATURAL JOIN (
         SELECT   cID, MAX(OffDATE) OffDATE
         FROM     offer
         GROUP BY cID
       ) t) ON off.cID = c.ID

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

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