简体   繁体   English

MySQL加入和条件

[英]MySQL Join with And condition

I am using this SQL code to select random entries from a question table. 我正在使用此SQL代码从问题表中选择随机条目。

I would like to add a condition to this query. 我想为此查询添加条件。 Basically the table has a user id record to keep track of who added the question. 基本上,该表具有用户ID记录,以跟踪谁添加了问题。 This id record shall now be used on conjunction with the Join Query. 现在,该id记录应与Join Query结合使用。

Basically: Select random question entry AND verify it belongs to the given user id. 基本上:选择随机问题条目并确认它属于给定的用户ID。

SELECT *
  FROM Questions JOIN
       (SELECT CEIL(RAND() *
                    (SELECT MAX(Question_ID)
                       FROM Questions )) AS Question_ID
        ) AS r2
       USING (Question_ID) ;

I tried adding the condition like this: 我尝试添加如下条件:

And UID='$user_ID'

However I am getting a blank page as a result so I guess by adding the condition like this, I am messing up the entire query. 但是我得到的结果是空白页,所以我想通过添加这样的条件,我弄乱了整个查询。 Basically, I can't figure up how to put the condition... 基本上,我不知道该如何处理...

SELECT *
  FROM Questions JOIN
       (SELECT CEIL(RAND() *
                    (SELECT MAX(Question_ID)
                       FROM Questions WHERE UID='$user_ID')) AS Question_ID
        ) AS r2
       USING (Question_ID) ;

The '' quotes in PHP denotes a literal string whereas "" input variables, they're not interchangeable. PHP中''引号表示文字字符串,而输入变量""则不可互换。 If using '' 's you can input variables by doing '{$var}' . 如果使用'' ,则可以通过执行'{$var}'输入变量。

If your table is very large it would be slow to run a RAND() over it and would be better to pass a random id generated in PHP. 如果表很大,则在其上运行RAND()会很慢,并且最好传递PHP中生成的随机ID。

Random from PHP: 来自PHP的随机代码:

SELECT *
FROM Questions as q
WHERE q.UID = $user_ID AND q.ID = $randomID;\

Random from SQL: 来自SQL的随机数:

SELECT *
FROM Questions as q
WHERE q.UID = $user_ID
ORDER BY RAND()
LIMIT 1;

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

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