组合或交叉多个MySQL命令

时间:2017-01-29 13:04:42

标签: php mysql sql inner-join intersect

我必须在两张桌子上搜索。

我的第二张表是:

SAVEPOINT

我的第一张表只包含用户信息。

  • 如果我使用以下MySQL命令,我将得到一个结果:

    public static void main(String ar[]){
    short [] array =new short[255];
    Random rand = new Random();
    int random_integer;
    boolean   flag=false;
    for (int i=0;i<array.length;i++){
         random_integer = rand.nextInt();
         for (int j=0;j<i;j++){
             if ((short)random_integer==array[j]){
                     flag=true;
                     i--;
                }
          }
          if (flag==false)
            array[i]=(short)random_integer;  
    }
    for (int i=0;i<array.length;i++)
        System.out.print(" "+array[i]);
    System.out.println();
    }
    
  • 如果我使用以下MySQL命令,我也会得到一个结果(我只是将“is_first_time”值更改为“0”:

    +---------+---------------+-------+
    | user_id | is_first_time | score |
    +---------+---------------+-------+
    |   44    |       1       |   20  |
    +---------+---------------+-------+
    |   44    |       0       |   20  |
    +---------+---------------+-------+
    
  • 但如果我将两个命令与AND结合使用,我将不会得到任何结果:

    SELECT * , users_score.user_id users_score_user_id 
    FROM users JOIN users_score 
    ON users_score.user_id = users.id 
    WHERE (users_score.score='20' AND users_score.is_first_time='1')
    

如何组合或交叉两个命令?

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

您需要在此使用OR条件

WHERE (users_score.score='20' AND users_score.is_first_time='1') 
  OR  (users_score.score='20' AND users_score.is_first_time='0')

但是可以使用IN条件

以更好的方式编写它
SELECT *,
       users_score.user_id users_score_user_id
FROM   users
       JOIN users_score
         ON users_score.user_id = users.id
WHERE  users_score.score = '20'
       AND users_score.is_first_time IN ( '1', '0' ) 

答案 1 :(得分:0)

如果您希望两个条件均为真的用户,则一种方法使用inexists

SELECT u.* 
FROM users u
WHERE u.id IN (SELECT us.user_id FROM users_score us WHERE us.score = '20' AND us.is_first_time = '0'
              ) AND
      u.id IN (SELECT us.user_id FROM users_score us WHERE us.score = '20' AND us.is_first_time = '1'
              );

AND的问题是单行不能同时为0和1。

如果您只想要用户ID,我建议您group byhaving

select us.user_id
from users_score us
where score = 20 and us.is_first_time in (0, 1)
group by us.user_id
having count(distinct us.is_first_time) = 2;

请注意,我删除了单引号。如果列是数字,则不要使用单引号进行比较。 (当然,如果它们是字符串,则使用单引号。)