表1: - tbl_contacts
字段
user_id
contact_id
first_name
last_name
表2: - tbl_phone_details
字段
contact_id
phone_number
phone_type
表3: - tbl_email_details
字段
contact_id
email_address
email_type
QUERY -
SELECT
tbl_contacts.*, tbl_email_details.*, tbl_phone_details.*
FROM
tbl_contacts, tbl_email_details,
tbl_phone_details
WHERE
tbl_contacts.user_id = '1'
我想获取特定user_id的first_name,last_name,Phone和Email详细信息。我已经使用了上面的查询,但它给了我重复的结果,而且我对DB查询(如JOIN和INNER QUERY)的了解较少。
如果有任何想法,请帮助。
需要输出: -
contact_id,first_name,last_name,phone_number,phone_type,email_address,email_type (此处电子邮件和电话号码可以为特定用户提供一个或多个值。)
答案 0 :(得分:1)
试试这个
如果要检索特定ID的数据
SELECT T.contact_id,
T.first_name,
T.last_name,
P.phone_number,
P.phone_type,
E.email_address,
E.email_type
FROM tbl_contacts T LEFT JOIN tbl_phone_details P ON
T.contact_id = P.contact_id
LEFT JOIN tbl_email_details E ON
T.contact_id = E.contact_id
WHERE T.contact_id = @contact_id
如果要检索所有数据
SELECT T.contact_id,
T.first_name,
T.last_name,
P.phone_number,
P.phone_type,
E.email_address,
E.email_type
FROM tbl_contacts T LEFT JOIN tbl_phone_details P ON
T.contact_id = P.contact_id
LEFT JOIN tbl_email_details E ON
T.contact_id = E.contact_id
答案 1 :(得分:0)
SELECT tbl_contacts。*,tbl_email_details。*,tbl_phone_details。* FROM tbl_contacts,tbl_email_details,tbl_phone_details WHERE tbl_contacts.user_id ='1'
你忘了提及加入所有表格的条件!
SELECT c.first_name, c.last_name, p.phone_number, e.email_address
FROM tbl_contacts c, tbl_email_details e, tbl_phone_details p
WHERE tbl_contacts.user_id = '1'
AND c.contact_id = e.contact_id
AND e.contact_id = p.contact_id;
答案 2 :(得分:0)
这就是我用JOIN做出这个请求的方式......但是可能会有更好或更快的方法来实现它。
SELECT first_name, last_name, phone_number, email_address
FROM tbl_contacts
JOIN tbl_phone_details
ON tbl_contacts.contact_id=tbl_phone_details.contact_id
JOIN tbl_email_details
ON tbl_email_details.contact_id=tbl_contacts.contact_id
WHERE tbl_contacts.user_id = '1';
这样你就不会迷失在这里的所有不同答案中(可能都是正确的):
contact_id
,那么您应该决定哪一个(例如tbl_phone_details.contact_id)答案 3 :(得分:0)
SELECT c.contact_id, c.first_name, c.last_name,
phone.phone_number, phone.phone_type,
email.email_address, email.email_type
FROM tbl_contacts c
LEFT JOIN tbl_email_details email ON c.contact_id = email.contact_id
LEFT JOIN tbl_phone_details phone ON c.contact_id = phone.contact_id
WHERE tbl_contacts.user_id = '1'
答案 4 :(得分:0)
Sql查询易于学习和编写,它们在从数据库中获取重要数据时非常有用。 Joins
用于基本上从两个表中基于公共列的两个或多个表中获取数据
Inner Join
将选择两个表中常见的值
Left Join
将从左表中选择所有数据,Right Join
将根据ID从右表中选择所有数据。
这些是SQL的基础知识,您必须知道如何使用它们获取准确的数据。