MySQL组合2个查询

时间:2013-05-30 15:38:40

标签: mysql

有人可以帮我结合以下2个问题吗?目标是在php中创建Speaker和Organizer变量(也在下面)。谢谢!

$query= "
SELECT srMeet.mOrg, srMeet.mSpeaker, users.uID, users.uFirst, users.uLast
FROM srMeet 
INNER JOIN users
ON users.uID = srMeet.mSpeaker";

$query= "
SELECT srMeet.mOrg, srMeet.mSpeaker, users.uID, users.uFirst, users.uLast
FROM srMeet 
INNER JOIN users
ON users.uID = srMeet.mOrg";


$Speaker = $row['uFirst'] . " " . $row['uLast'];

$Organizer = $row['uFirst'] . " " . $row['uLast'];

3 个答案:

答案 0 :(得分:1)

您可以在查询中多次加入同一个表,并使用AS为其指定别名。 AS关键字实际上是可选的,但我总是将其作为备注包含在自己身上。

这里的INNER JOIN意味着每次会议都必须有组织者和发言者。如果有可能在没有组织者或演讲者的情况下召开会议,您可能希望使用LEFT OUTER JOIN s并做一些事情来处理NULL值。

SELECT CONCAT(s.uFirst, ' ', s.uLast) AS speaker, 
  CONCAT(o.uFirst, ' ', o.uLast) AS organizer
FROM srMeet 
INNER JOIN users AS s
ON users.uID = srMeet.mSpeaker
INNER JOIN users AS o
ON users.uID = srMeet.mOrg;


$Speaker = $row['speaker'];

$Organizer = $row['organizer'];

答案 1 :(得分:1)

假设会议有一个发言人和一个组织者,您可以使用联接来获取单行会议的详细信息。

$query= "SELECT srMeet.mOrg, 
            srMeet.mSpeaker, 
            UserSpeaker.uID AS SpeakerUid, 
            UserSpeaker.uFirst AS SpeakerFirst, 
            UserSpeaker.uLast AS SpeakerLast, 
            UserOrganizer.uID AS OrganizerUid, 
            UserOrganizer.uFirst AS OrganizerFirst, 
            UserOrganizer.uLast AS OrganizerLast
        FROM srMeet 
        INNER JOIN users UserSpeaker
        ON UserSpeaker.uID = srMeet.mSpeaker
        INNER JOIN users UserOrganizer
        ON UserOrganizer.uID = srMeet.mOrg";

答案 2 :(得分:0)

为什么不使用 UNION

$query= "
SELECT srMeet.mOrg, srMeet.mSpeaker, users.uID, users.uFirst, users.uLast
FROM srMeet 
INNER JOIN users
ON users.uID = srMeet.mSpeaker
UNION
SELECT srMeet.mOrg, srMeet.mSpeaker, users.uID, users.uFirst, users.uLast
FROM srMeet 
INNER JOIN users
ON users.uID = srMeet.mOrg"