简体   繁体   中英

How to get data with condition SQL QUERY

So first of all, I have 2 table. The first one is the categories

Id     Name     
------------
1   Interior      
2   Eksterior    
3   Display

then the secon table is history which the data is the task I've finished

Id     category_name    category_id    date (month)     User Id 
---------------------------------------------------------------
001    Interior            1               3             1084
002    Eksterior           2               3             1084
003    Interior            1               4             1089
004    Eksterior           2               4             1085
005    Display             3               4             1085

and what I want is to get categories by month, user id and know which one already done and not done from history, like this

example the data in March with user id 1084:

Id     Name     Status     
---------------------------
1   Interior     done      
2   Eksterior    done      
3   Display    not done    

or like this:

Id     Name     Status    
--------------------------
1   Interior     1       
2   Eksterior    1       
3   Display      0       

if the category in history table exist, the status will be 1 for done and 0 for not done.

this is my query before:

SELECT c.id, c.category, c.id=h.category_id status FROM categories c, history h WHERE MONTH(h.created_at)

I keep retrieving the wrong result for my query. Please help me..

Seems like:

SELECT * 
FROM 
  categories c
  LEFT JOIN history h on h.category_id = c.id AND h."date (month)" = 3

..will get you towards what you want: there will be NULL in the row from history table, for category Display; you can use this "is or is not null" to create your done/not done column

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