SQL Query to check if student has 1 course with student 2

I have one table and I need to check if two users for which I have identifiers (for example, 20 and 21) have the same course, only true or false.

Table: jos_gj_users
Columns: id_user, id_group

Data Example: (20; 4)
              (20; 5)
              (20; 6)
              (21; 6)
              (21; 7)

The data above shows that user 20 and user 21 are sharing course 6, but how can I get this with SQL by simply entering identifiers and not looping the results with PHP?

+3
source share
6 answers

Try self-connect:

SELECT T1.id_group
FROM jos_gj_users T1
JOIN jos_gj_users T2
ON T1.id_group = T2.id_group
WHERE T1.id_user = 20
AND T2.id_user = 21

" " , , , , .

SQL, SELECT, EXISTS:

SELECT CASE WHEN EXISTS
(
    SELECT T1.id_group
    FROM jos_gj_users T1
    JOIN jos_gj_users T2
    ON T1.id_group = T2.id_group
    WHERE T1.id_user = 20
    AND T2.id_user = 21
) THEN 1 ELSE 0 END AS result

0 (false), 1 (true).

+3

, . 1, 2. , , , id_group , :

SELECT count(*)
FROM jos_gj_users As j1, jos_gj_users As j2
WHERE j1.id_user = 20 AND j2.id_user = 21
AND j1.id_group = j2.id_group

: . 0, .

0

:

select id_group
from  jos_gj_users
where (id_user = 20)
and id_group in (select id_group from jos_gj_users where id_user = 21)
0
SELECT COUNT(*) > 0 FROM jos_gj_users WHERE id_user=54321 AND id_group IN ( SELECT id_group FROM jos_gj_users WHERE id_user = 1345 )
0

, .

SELECT
  *
FROM
  jos_gj_users T1
  INNER JOIN jos_gj_users T2 ON T1.id_group = T2.id_group
0

Try this attempt - it takes input parameters in the first bold region and returns the value TRUE or FALSE through the CASE statement, based on the values ​​in the second bold regions.

SELECT DISKRITNY CASE WHEN
(SELECT DISTINCT COUNT (id_group) FROM jos_gj_users WHERE id_user IN (20, 21)
GROUP BY id_group
HAYING COUNT (DISTINCT id_user) = 2) is not any 'TRUE'
ELSE "FALSE"
END
FROM jos_gj_users

0
source

Source: https://habr.com/ru/post/1780116/


All Articles