-1

I have a challenge trying to merge output using PHP from two TABLES in a MySQL database. I am not sure how to put the SELECT string to get certain columns from both of the TABLES I want to pull data from.

In one TABLE I have a unique identifier (bid) and this identifier is also present in the second TABLE.

The first TABLE represents a ticket buyer (table name = eventoslotickerbuyer). And the second TABLE represents guests (table name = eventosloguests). The structure of the eventosloticketbuyer TABLE looks like this:

bid
firstname
lastname
email
cellphone
privatekey
eventid
orderdatetime
confirmeddatetime

The eventosloguests TABLE has the following structure:

gid
gfirstname
glastname
gemail
bid
eventid
registered
confirmed
confcode

What I want to accomplish, is to pull firstname and lastname from the "first" table, then pull gfirstname and glastname from the "second" table. The column that exists in both tables are the bid.

I can't figure out how the query should look like, so would appreciate some help.

Sincerely, Andreas

UPDATE:

I got it to work buy writing the query like this:

SELECT a.firstname, a.lastname, b.gfirstname, b.glastname
FROM eventosloticketbuyer a
INNER JOIN eventosloguests b ON a.bid = b.bid

What I still do not know is, if there is no GUEST connected to a BUYER, would this end up in blanks or should I switch it in some way to secure that I fetch the BUYER by using the GUEST as source?

4

1 回答 1

1

您需要 JOIN 表,例如使用 INNER JOIN 从两个表中选择所有具有相同的记录bid

SELECT buyers.firstname, buyers.lastname, guests.gfirstname, guests.lastname
FROM
  buyers INNER JOIN guests
  ON buyers.bid = guests.bid

您还可以使用别名编写上述查询,以缩短编写时间:

SELECT b.firstname, b.lastname, g.gfirstname, g.lastname
FROM
  buyers b INNER JOIN guests g
  ON b.bid = guests.bid

b 只是买家的别名,g 是客人的别名。使用 INNER JOIN,您可以从买家表中返回所有行,这些行具有与来宾表中的行匹配的记录。如果有更多匹配的行,INNER JOIN 将执行所有这些行的乘法。

如果有一些买家出价但没有客人出价,那么他们将不会被退回。但是您可以使用 LEFT JOIN:

SELECT b.firstname, b.lastname, g.gfirstname, g.lastname
FROM
  buyers b LEFT JOIN guests g
  ON b.bid = guests.bid

这将返回所有买家和所有匹配的客人。如果没有匹配,guests 表的所有值都将为 NULL。您还可以有一个 RIGHT JOIN 来返回客人的所有行,并且只返回匹配的买家(或者您可以交换买家和客人的顺序)。

您可以查看SQL 连接的可视化解释,以了解有关连接的更多信息。

于 2013-07-01T15:42:23.577 回答