Home > Back-end >  How to get uncommon column values associated with two different rows in a MYSQL table
How to get uncommon column values associated with two different rows in a MYSQL table

Time:05-21

I am trying to query a table with thousands of rows using php to retrieve any uncommon column values associated with two rows. The sample table above has two columns A and B. I would like to get the value in column B that is not associated with both column A values 1 and 2. In this short example that would be 5.

I have tried the following codes below with no luck: Thanks.

Table
 - - 
|A|B|
 - - 
|1|3|
 - - 
|1|4|
 - - 
|1|5|
 - - 
|2|3|
 - - 
|2|4|
 - - 
|3|3|
 - - 

$records = mysqli_query($link, "select DISTINCT B from Table WHERE A = '1' && A = '2'");
($row = mysqli_fetch_array($records)); 
$result  = $row['B'];

//OR

$records = mysqli_query($link, "select B from Table WHERE A = '1' && NOT A = '2'");
($row = mysqli_fetch_array($records)); 
$result  = $row['B'];

CodePudding user response:

I would use aggregation:

SELECT B
FROM yourTable
GROUP BY B
HAVING SUM(A = 1) = 0 OR SUM(A = 2) = 0;

CodePudding user response:

you can try this

SELECT B FROM(
select B, COUNT(B) CNT
from test
WHERE A IN (1,2)
GROUP BY B)X WHERE CNT=0 OR CNT=1;
  • Related