2014-12-03 101 views
2

我有两个表:InvoiceMySQL Query;结合两个表

id number date  client end client city vracht 
    1 4271 2014-5-28 ALLIN STIHO  ZWOLLE 0 

Materials

id number material thickness length width amount price 
    1 14271 Ocoume   10 2500 1220 150 2,3 
    2 14271 Ocoume   15 2500 1220  60 2,3 
    3 14271 Ocoume   18 2500 1220 125 2,3 
    4 14271 Ocoume   22 2500 1220  44 2,3 
    5 14271 Ocoume   40 2150 1000  72 2,3 
    6 14271 Ocoume   18 3100 1530  25 2,3 

Invoice表中是发票。在Materials表中是属于发票的资料。

我想要的是那些相结合,其中有(表中的数字列)相同的发票编号,与选择的查询,像这样:

number date  client end client city vracht material thickness length width amount price 
14271 2014-5-28 ALLIN STIHO  ZWOLLE  0 Ocoume   10 2500 1220 150 2,3 
14271 2014-5-28 ALLIN STIHO  ZWOLLE  0 Ocoume   15 2500 1220  60 2,3 
14271 2014-5-28 ALLIN STIHO  ZWOLLE  0 Ocoume   18 2500 1220 125 2,3 
14271 2014-5-28 ALLIN STIHO  ZWOLLE  0 Ocoume   22 2500 1220  44 2,3 
14271 2014-5-28 ALLIN STIHO  ZWOLLE  0 Ocoume   40 2150 1000  72 2,3 
14271 2014-5-28 ALLIN STIHO  ZWOLLE  0 Ocoume   18 3100 1530  25 2,3 

这将如何查询看看吗?

+3

你想要一个JOIN。 – 2014-12-03 09:17:00

+0

@ shree.pat18如何使用JOIN? – 2014-12-03 09:17:52

+0

检查内部连接 – 2014-12-03 09:17:55

回答

3
select 
    `f`.`number`, 
    `f`.`client`, 
    `f`.`eind_client`, 
    `f`.`city`, 
    `f`.`vracht`, 
     `m`.`material`, 
     `m`.`thickness`, 
     `m`.`length`, 
     `m`.`width`, 
     `m`.`amount`, 
     `m`.`price` 
from 
    `invoice` as `f` 
right outer join 
    `materials` as `m` 
on 
    `f`.`number`=`m`.`number` 
+0

这个作品很好,但并不完美..每个材料记录显示6次..你知道如何解决这个问题吗? – 2014-12-03 09:38:08

+1

也许试试加入使用左(或右)外连接。 – starko 2014-12-03 09:40:09

+0

好吧,正确加入作品..我也加了group by,所以如果你接受我的编辑,我可以接受你的回答:) – 2014-12-03 09:57:36

3
select * from invoice, materials where invoice.number=materials.number 

取而代之*的,建议记下所需的列..

+1

您应该使用JOIN关键字以及连接的类型而不是此样式。 – 2014-12-03 09:22:38

+0

@ shree.pat18这基本上是内部连接,如果你想写内部连接这个词,它会像..从invoice内部连接材料select * from invoice.number = materials.number – 2014-12-03 09:23:36

+0

有一个单个字符的错字,但是该网站至少需要6个字符的编辑。烤羊! – Persixty 2014-12-03 09:24:24

1

您可以使用JOIN来从两个表中获取列。

例如:

SELECT * 
FROM 
    Invoice AS i, 
    Materials AS m, 
WHERE 
    m.number = i.number 
    AND 
    m.number = 14271 
+0

这只会减少14271号的结果。 – 2014-12-03 09:25:48

+0

@DanyalSandeelo:看完这个问题了吗?从表3可以看出,除14271之外没有其他数字。 – 2014-12-03 09:27:37

+0

这只是一个示例数据,当然他必须查看所有发票。 – 2014-12-03 09:29:08

1

您可以使用加入。

SELECT * FROM Material as M LEFT JOIN Invoice as I ON I.number=M.Number 
2

如前所述,如果你有一个外键关系,你可以使用JOIN.这应该给你想要的结果。

你可以使用:

Select "columns you need " or "* "from invoice, materials 
WHERE invoice.number = material.number 
+0

这不是UNION的工作原理。 UNION将组合结果集,即集合1和集合2,它不会将集合2的列添加到集合1的列中,这是OP需要的。 – 2014-12-03 09:29:57

+0

不适用于UNION ALL吗? – Haris 2014-12-03 09:33:43

+0

没有。看看这个:http://stackoverflow.com/questions/905379/what-is-the-difference-between-join-and-union – 2014-12-03 09:36:29