我有三张桌子而不是管理不同的社交媒体帐户 - facebook,twitter和linkedin。以下查询将返回Facebook帐户正常但没有别的 - 我做错了什么?每个表都通过user_id字段链接,但每个记录也有自己的id字段。
SELECT
bla_facebook_accts.id as facebook,
bla_linked_in_accts.id as linkedin,
bla_twitter_accts.id as twitter
FROM
bla_facebook_accts
LEFT OUTER JOIN
bla_linked_in_accts
ON
(bla_linked_in_accts.user_id = bla_facebook_accts.user_id)
LEFT OUTER JOIN
bla_twitter_accts
ON
(bla_linked_in_accts.user_id = bla_twitter_accts.user_id)
WHERE bla_facebook_accts.user_id = '12';
我出错的任何想法 - 我只想让它返回一行,如果用户在每个网络上都有一个帐户 - 即每张表中的记录
答案 0 :(得分:2)
您的查询的问题是,如果用户没有Facebook帐户,那么您将无法获得有关此用户的任何信息。如果用户没有linkedin帐户,那么您将无法获得有关其Twitter帐户的信息。 LEFT JOINS不适用于此目的,但MySQL不支持FULL OUTER JOINS,因此作为解决方法,您可以执行以下操作:
select
(select id from bla_facebook_accts where user_id = user.user_id) as facebook,
(select id from bla_linked_in_accts where user_id = user.user_id) as linkedin,
(select id from bla_twitter_accts where user_id = user.user_id) as twitter
from
(select 12 user_id) user
答案 1 :(得分:1)
如果你想返回一个在所有表中都有记录的行,我想你想使用INNER JOIN
。
SELECT
f.id as facebook,
l.id as linkedin,
t.id as twitter
FROM
bla_facebook_accts f
INNER JOIN bla_linked_in_acctsn l ON f.user_id = l.user_id
INNER JOIN bla_twitter_accts t ON f.user_id = t.user_id
答案 2 :(得分:1)
关于没有FB帐户的评论:
(SELECT 'Facebook' as 'ac', id FROM bla_facebook_accts WHERE user_id=12)
UNION
(SELECT 'LinkedIn' as 'ac', id FROM bla_linked_in_accts WHERE user_id=12)
UNION
(SELECT 'Twitter' as 'ac', id FROM bla_twitter_accts WHERE user_id=12)
答案 3 :(得分:1)
如果您要列出给定用户的所有现有帐户,无论该用户拥有多少帐户,LEFT JOIN
(又名LEFT OUTER JOIN
)都是正确的方法,但您必须加入你知道的东西将存在于所有用户。因此,您应该将查询基于用户表,并加入用户表中user_id的所有表。
将userTable
重命名为您的用户表格
SELECT
facebook.id as facebook,
linkedin.id as linkedin,
twitter.id as twitter
FROM
userTable
LEFT JOIN
bla_facebook_accts facebook ON (userTable.user_id = facebook.user_id)
LEFT JOIN
bla_linked_in_accts linkedin ON (userTable.user_id = linkedin.user_id)
LEFT JOIN
bla_twitter_accts twitter ON (userTable.user_id = twitter.user_id)
WHERE
userTable.user_id = 12
答案 4 :(得分:0)
尝试:
从表左外连接(t1,t2,t3)上选择t1.column,t2.column,t2.column(t1.user_id = table.user_id AND t2.user_id = table.user_id AND t3.user_id = table .user_id)
等
答案 5 :(得分:0)
如果您尝试使用linkedin ID进行第二次加入,如果您的用户没有linkedin帐户但拥有Facebook帐户,则永远不会得到答案。您需要始终使用您的源帐户(facebook)
加入SELECT
bla_facebook_accts.id as facebook,
bla_linked_in_accts.id as linkedin,
bla_twitter_accts.id as twitter
FROM
bla_facebook_accts
LEFT OUTER JOIN
bla_linked_in_accts
ON
(bla_linked_in_accts.user_id = bla_facebook_accts.user_id)
LEFT OUTER JOIN
bla_twitter_accts
ON
(bla_linked_in_accts.user_id = bla_facebook_accts.user_id)
WHERE bla_facebook_accts.user_id = '12';