从2个表中提取数据

时间:2014-02-13 09:06:36

标签: mysql

我有2张桌子

table1

eventcode       mobile         points   name
-------------
CAMTRIP         82074626         10      SS
TARANAKI        91262063         30      JL
CAMTRIP         91262063         10      JL

和table2

passcode    serial  remark
----------
TARANAKI        1   NZ 
CAMTRIP         2   Cameroon

我希望输出为

Cameroon
NAME Points
----------
SS   10
JL   10

NZ
----------
JL   30

我正在尝试

SELECT ( b.name )      name, 
       ( b.points )    point, 
       ( b.eventcode ) ecode, 
       ( c.remark )    rem 
FROM   table1 b, 
       table2 c 
WHERE  c.passcode = b.eventcode 
GROUP  BY b.eventcode 

我没有得到理想的结果。怎么了?

5 个答案:

答案 0 :(得分:3)

所以我猜你需要的实际结果是:

Remark    Name  Points
----------------------
Cameroon  SS    10
Cameroon  JL    10
NZ        JL    30

制作喀麦隆和NZ组头应该在客户端完成。对此的查询将是:

SELECT t2.Remark, t1.Name, t1.Points
FROM table2 t2
INNER JOIN table1 t1 ON t2.passcode = t1.eventcode

在共享字段上只需JOIN,然后SELECT您希望从每个表中添加任何字段。

答案 1 :(得分:0)

尝试:

$query = "Select b.name as name, b.points as points, b.eventcode as ecode, c.remark as rem from table1 b join table2 c ON (c.passcode=b.eventcode) group by b.eventcode";

答案 2 :(得分:0)

SELECT  b.name  as    name, 
        b.points as    point, 
        b.eventcode as ecode, 
       GROUP_CONCAT(DISTINCT c.remark.has SEPARATOR ", ") as    rem 
FROM   table1 b 
left outer join table2 c on c.passcode = b.eventcode 
GROUP  BY c.passcode 

答案 3 :(得分:0)

试试这个

select table2.remark,table1.name,table1.points from table1,table2 where  
table1.eventcode=table2.passcode

答案 4 :(得分:0)

数据库响应中没有现实的理由需要通过备注来分解行,因为这只会使人类用户查看结果,而不是响应的目的。将结果分解为更容易查看的内容应该由UI层处理。考虑到这一点,以下内容将得到您想到的结果,以便其他一些过程可以轻松地为报告准备数据:

SELECT remark, name, points
FROM table1
LEFT JOIN table2 ON eventcode = passcode

哪会回来:

remark     name  points
------------------------
Cameroon   SS    10
Cameroon   JL    10
      NZ   JL    30
相关问题