mysql加入问题

时间:2011-07-22 07:34:50

标签: mysql join

table a
-------------------------------------------------
id   name     wishlist1    wishlist2     wishlist3

1    john      1              2            3
2    paul      4              5


table b
--------------------------------------------------
id    goods

1     car
2     aircraft
3     bicycle
4     motorbike
5     ipad


result i want to get
---------------------------------------------------
john    car        aircraft    bicycle
paul    motorbike  ipad

我怎么能得到这个结果? (在mysql中)

4 个答案:

答案 0 :(得分:5)

这会输出最多3个愿望(如果没有愿望,则在愿望列中显示空值)

select
  name,
  g1.goods as wish1,
  g2.goods as wish2,
  g3.goods as wish3
from tablea a
left join tableb g1.id on g1.wishlist1
left join tableb g2.id on g1.wishlist2
left join tableb g3.id on g1.wishlist3

这可能会更好,如果你不介意以逗号分隔的愿望清单,那就更好了:

select
  name,
  group_concat(goods) as wishes
from tablea a
left join tableb b on b.id in (a.wishlist1, a.wishlist2, a.wishlist3)
group by name;

将输出:

name  |  wishes
------|----------------------
john  |  car,aircraft,bicycle
paul  |  motorbike,ipad

答案 1 :(得分:3)

这不是一个好的数据库设计。

您应该创建一个intermadiary表,如:

table a_b
-----------
id_a int
id_b int

通过这种方式,您将成功建模m到n的关系,这样用户可以在心愿单中包含多个元素,并在多个心愿单中显示元素

答案 2 :(得分:3)

SELECT
   a.name,
   b1.goods,
   b2.goods,
   b3.goods
FROM
   a
   LEFT JOIN
   b AS b1 ON a.wishlist1 = b1.id
   LEFT JOIN
   b AS b2 ON a.wishlist2 = b2.id
   LEFT JOIN
   b AS b3 ON a.wishlist3 = b3.id

如果您总是有3个心愿单项目,那么这就差不多了。如果您想扩展心愿单项目的数量,那么您最好使用单独的表并将其存储为行。见First Normal Form

答案 3 :(得分:3)

这通常是一个坏主意。我建议按如下方式构建表:

person
pid name
--- ----
 1  john
 2  paul

good
gid item
--- ---------
 1  car
 2  aircraft
 3  bicycle
 4  motorbike
 5  ipad

person_wants_good
pid gid
--- ---
 1   1
 1   2
 1   3
 2   4
 2   5

然后,要获得所需的结果,请使用以下查询:

SELECT p.name, g.good
  FROM person_wants_good
  JOIN person USING (pid)
  JOIN good USING (gid)

这将返回下表:

 name good
 ---- ---------
 john car
 john aircraft
 john bicycle
 paul motorbike
 paul ipad

然后由您的客户端代码以交叉表格的形式呈现此信息。