SELECT JOIN重复

时间:2016-11-02 08:02:47

标签: php mysql

我有3个表的数据库,如:

服务
    

   id | name | service_id (UNIQUE)
    1  | new  |    123
    2  | service1  |    543

计数
    

   id | counts | counts_price | service_id
    1  | 100    |     200      | 123
    5  | 200    |     250      | 123
    6  | 300    |     350      | 543

背景
    

   id | background | background_price | service_id
    1  |   white    |        50        | 123
   12  |   red      |        150        | 123
    

我的查询如下:

Eff

:service_id = 123
在输出中我得到了     var_dump

为什么它重复?查询有什么问题?

SELECT background.background, services.name, counts.count 
FROM services INNER JOIN background 
ON background.service_id=services.service_id INNER JOIN counts 
ON counts.service_id=services.service_id 
WHERE services.service_id = :service_id

3 个答案:

答案 0 :(得分:1)

为此添加group by

GROUP BY services.service_id

所以你的最终查询是:

SELECT background.background, services.name, counts.count, services.service_id 
FROM services INNER JOIN background 
ON background.service_id=services.service_id INNER JOIN counts 
ON counts.service_id=services.service_id 
WHERE services.service_id = :service_id
GROUP BY services.service_id

答案 1 :(得分:0)

我认为您的问题是您的数据不知道哪些背景与哪些背景相关联。在这个简单的例子中,你可以生成行号以帮助这样的事情 -

select  t.background
         ,se.name
         ,s.counts_price
from
(
select c.*,
            if(c.service_id<> @p, @rn:=1,@rn:=@rn+1) rownumber,
            @p:=c.service_id p
from    (select @rn:=0,@p:=0) rn,counts c
order   by c.service_id,c.id
) s
join
(
select b.*,
            if(b.service_id<> @p1, @rn1:=1,@rn1:=@rn1+1) rownumber1,
            @p1:=b.service_id p
from    (select @rn1:=0,@p1:=0) rn,background b
order   by b.service_id,b.id
) t on t.service_id = s.service_id and t.rownumber1 = s.rownumber

join services se on se.service_id = s.service_id

结果

+------------+------+--------------+
| background | name | counts_price |
+------------+------+--------------+
| white      | new  |          200 |
| red        | new  |          250 |
+------------+------+--------------+

答案 2 :(得分:0)

根据你的输出

 SELECT background.background, services.name, counts.count 
 FROM services INNER JOIN background 
 ON background.service_id=services.service_id INNER JOIN counts 
 ON counts.service_id=background.service_id AND counts.id != background.id
 WHERE services.service_id = 123

希望它能够满足您的需求