English 中文(简体)
MySQL条件联接
原标题:MySQL Conditional Join

正如您在下面看到的,我正在检查当前用户是否位于表friendsuser_auser_b列中。

根据当前用户的位置,我想找到他相应的朋友。

不知怎么的,我无法使用这种语法,并且想知道是否有人能告诉我出了什么问题(我在if user_a=2附近的第3行遇到了一个错误。

SELECT *
  FROM friends
IF user_a = 2 THEN
  JOIN user_profiles ON friends.user_b = user.profiles.user_id
 WHERE user_a = 2
   AND accepted = 1;
ELSEIF user_b = 2 THEN
  JOIN user_profiles ON friends.user_a = user_profiles.user_id
 WHERE user_b = 2
   AND accepted = 1;
END IF;
最佳回答

您可以使用UNION:

select f.*, up_a.* from friends f
  inner join user_profiles up_a on f.user_a=up_a.user_id
  where f.user_b=2 and f.accepted=1
union
select f.*, up_b.* from friends f
  inner join user_profiles up_b on f.user_b=up_b.user_id
  where f.user_a=2 and f.accepted=1;
问题回答

你在发明语法。MySQL中的“IF”支持如下:

  1. Statement, for use in stored procedures and triggers. Docs: http://dev.mysql.com/doc/refman/5.0/en/if-statement.html

  2. 函数,用于为结果列选择一个备用表达式。文档:http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html#function_if

你似乎完全在做别的事情。

我认为您尝试使用的语法不受支持。我认为不能使用IF条件以这种方式分支SQL语句。可以将其放入<code>SELECT CASE</code>中。

如果可以使用局部变量,则可以使用以下方法:

BEGIN
SELECT user_a, user_b INTO local_a, local_b FROM friends;

IF local_a = 2 THEN
  SELECT * FROM friends JOIN user_profiles ON friends.user_b = users.profiles.user_id
  WHERE user_a = 2 AND accepted = 1;
ELSEIF user_b = 2 THEN
  SELECT * FROM friends JOIN user_profiles ON friends.user_b = users.profiles.user_id
  WHERE user_b = 2 AND accepted = 1
END IF;
END;

我也不确定这是否有效,但它可能会让你走上正确的道路。另请参阅:http://dev.mysql.com/doc/refman/5.0/en/select-into-statement.html





相关问题
SQL SubQuery getting particular column

I noticed that there were some threads with similar questions, and I did look through them but did not really get a convincing answer. Here s my question: The subquery below returns a Table with 3 ...

please can anyone check this while loop and if condition

<?php $con=mysql_connect("localhost","mts","mts"); if(!con) { die( unable to connect . mysql_error()); } mysql_select_db("mts",$con); /* date_default_timezone_set ("Asia/Calcutta"); $date = ...

php return a specific row from query

Is it possible in php to return a specific row of data from a mysql query? None of the fetch statements that I ve found return a 2 dimensional array to access specific rows. I want to be able to ...

Character Encodings in PHP and MySQL

Our website was developed with a meta tag set to... <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" /> This works fine for M-dashes and special quotes, etc. However, I ...

Pagination Strategies for Complex (slow) Datasets

What are some of the strategies being used for pagination of data sets that involve complex queries? count(*) takes ~1.5 sec so we don t want to hit the DB for every page view. Currently there are ~...

Averaging a total in mySQL

My table looks like person_id | car_id | miles ------------------------------ 1 | 1 | 100 1 | 2 | 200 2 | 3 | 1000 2 | 4 | 500 I need to ...

热门标签