简体   繁体   中英

MySQL SELECT with IF statement to set variable from another table

I want to show all the results from Table1 based on some select condition being true, and have a variable be set to 0 or 1 for each result from Table1 based on some satisfied condition with Table2.

SELECT * FROM Table1 WHERE Some_Condition=true

Foreach Table1.Name
    SELECT IF(TID IS NULL, 0, 1) AS Variable FROM Table2 
    WHERE 
        Table2.Name=Table1.Name AND Table2.Val='p' 

How can I make this all into one SQL call?

example call I would like to see is:

Table1:

+----+-------------------+
| ID |        Name       |
+----+-------------------+
| 1  |        John       |
+----+-------------------+
| 2  |        Alan       |
+----+-------------------+

Table2: So here Alan exists AND Val='p' , not just existing

+-------+-----------+-----+
|  TID  |    Name   | Val |
+-------+-----------+-----+
|   1   |    Alan   |  p  |
+-------+-----------+-----+

SQL result I want from a SINGLE SELECT statement:

+------+----------+
| Name | Variable | 
+------+----------+
| John |     0    |
+------+----------+
| Alan |     1    |
+------+----------+

A LEFT JOIN and a CASE statement may work for you. Please see query below.

SELECT A.Name AS item, (CASE WHEN B.Val='p' THEN 1 ELSE 0 END) AS Variable 
FROM Table1 A LEFT JOIN Table2 B ON (A.Name=B.Name)

I think you just want a JOIN:

SELECT t2.Name, IF(Tt2.ID IS NULL, 0, 1) AS Variable
FROM Table2 t2 JOIN
     Table1 t1
     ON t2.Name = t1.Name
WHERE t2.Val = 'p' AND <some condition on t1> = true;

In MySQL, you can simplify the SELECT to:

SELECT t2.Name, (Tt2.ID IS NOT NULL) AS Variable

Note that I added the name to the SELECT , although it is not in your sample SQL.

You need LEFT JOIN Table2 to include all rows from Table1 even if row in Table2 not exists. And then in Variable column just check if Table2.TID is presented (ie not null).

SELECT Name, (Table2.TID IS NOT NULL) AS Variable
FROM Table1
  LEFT JOIN Table2 ON Table2.Name=Table1.Name AND Table2.Val='p'

Or it can be done with IF() :

SELECT Name, IF(Table2.TID IS NULL, 0, 1) AS Variable
FROM Table1
  LEFT JOIN Table2 ON Table2.Name=Table1.Name AND Table2.Val='p'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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