简体   繁体   中英

Filter data based on specific column data in mysql

I have following tables in my database.

Table: actor_action

actor_id | time | monday_action_id | tuesday_action_id | .... | friday_action_id
1           1       2                   1                       3
1           2       3                   4                       1
2           1       1                   5                       4

Table: action

action_id | action_name | action_type | action_group_name
1               A1          single          -
2               X2          multiple        X_GROUP
3               B1          single          -
4               X1          multiple        X_GROUP
5               Y1          multiple        Y_GROUP

I want to query following details for given actor_id (eg: actor_id = 1). Here, as you can see, I want to select action_group_name instead of action_name if the action_type is " multiple ".

Expected output:-

actor_id | time | monday_name | tuesday_name | .... | friday_name
1           1       X_GROUP     A1                      B1
1           2       B1          X_GROUP                 A1

Currently I have following query which selects only the action name.

SELECT a1.action_name AS monday_name,
       a2.action_name AS tuesday_name,
       a3.action_name AS wednesday_name,
       a4.action_name AS thursday_name,
       a5.action_name AS friday_name,
       act.time AS time
FROM actor_action act
LEFT JOIN action a1 ON ct.monday_action_id=a1.action_id 
LEFT JOIN action a2 ON ct.tuesday_action_id=a2.action_id 
LEFT JOIN action a3 ON ct.wednesday_action_id=a3.action_id 
LEFT JOIN action a4 ON ct.thursday_action_id=a4.action_id 
LEFT JOIN action a5 ON ct.friday_action_id=a5.action_id 
WHERE act.actor_id = ?

How can I write a query that do the filtering as I mentioned above.

You just need to replace each of the individual column selects eg

a1.action_name AS monday_name

with an appropriate CASE expression:

CASE WHEN a1.action_type = 'multiple' THEN a1.action_group_name
     ELSE a1.action_name
END AS monday_name

Output (based on your sample data)

monday_name     tuesday_name    friday_name     time
X_GROUP         A1              B1              1
B1              X_GROUP         A1              2

Demo on dbfiddle

Note based on the table aliases in your query the table alias for this column should be a1 , not s1 .

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