简体   繁体   English

MYSQL SELECT使用或不使用外键从两个表中获取行

[英]MYSQL SELECT To fetch rows from two tables with or without a foreign key

I am looking for some help with a MYSQL query. 我正在寻找MYSQL查询的一些帮助。 I have two tables, one contains a list of tickets and the other is a list of members . 我有两个表,一个包含tickets列表,另一个是members列表。

Table Tickets: ticket_id, member_id Table Members: member_id 表票证:ticket_id,member_id表成员:member_id

A member can but doesn't have to be assigned to a ticket. 可以但不必将成员分配给票证。 What I would like to do is select all the tickets and then if the member_id field is set in the tickets table fetch the member information as well. 我想要做的是选择所有票证,然后如果在票证表中设置了member_id字段,也可以获取成员信息。

One approach is to do a SELECT * FROM Tickets and then loop through in PHP and check if the member_id field is set. 一种方法是执行SELECT * FROM Tickets ,然后在PHP中循环并检查是否设置了member_id字段。 If set then do another query on the members table to fetch the corresponding information. 如果设置,则在members表上执行另一个查询以获取相应的信息。 The only problem with this is that it would be a large number of queries. 唯一的问题是它会有大量的查询。

Is there any way to fetch all the results in one join query? 有没有办法在一个连接查询中获取所有结果?

Thanks 谢谢

Select *
from Tickets
Left Join Members On tickets.member_id = members.member_id
select * from tickets left outer join members on tickets.member_id = members.ticket_id
SELECT t.ticket_id, t.member_id FROM tikcets t LEFT JOIN members m ON t.member_id = m.member_id

This will give you all the tickets whether they have been assigned to a member or not. 这将为您提供是否已分配给会员的所有门票。 You should add to the query the additional fields that you want to fetch. 您应该在查询中添加要获取的其他字段。

Try this: 尝试这个:

SELECT t.ticket_id, m.member_id
FROM tickets AS t LEFT OUTER JOIN members AS m 
ON t.member_id = m.member_id

The LEFT OUTER JOIN will cause all results from tickets to be returned, and any match from members, not disqualifying the ticket records, so this could do the trick. LEFT OUTER JOIN将导致返回票证的所有结果,以及来自成员的任何匹配,而不是取消票证记录,因此这可以解决问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM