简体   繁体   中英

SQL query how to SELECT data even criteria not match in WHERE clause

I am sure there must be a relatively straightforward way to do this, but it is escaping me at the moment. Suppose I have a SQL table like this:

+-----+------+-----+-----+
|type |value |  Monthly  |
+=====+======+=====+=====+
|  a  |  5   |  Jan      |  << a,Jan      
+-----+------+-----+-----+
|  a  |  3   |  Feb      |  << a,Feb      
+-----+------+-----+-----+
|  a  |  7   |  April    |  << a,April    
+-----+------+-----+-----+

I group my query by type and monthly, let say i search for the value from jan to april, in this case, March doenst have any value, but i still want it to be display 0, how to do like this? :

+-----+------+-----+-----+
|type |value |  Monthly  |
+=====+======+=====+=====+
|  a  |  5   |  Jan      |  << a,Jan      
+-----+------+-----+-----+
|  a  |  3   |  Feb      |  << a,Feb      
+-----+------+-----+-----+
|  a  |  0   |  Mar      |  << a,Mar
+-----+------+-----+-----+
|  a  |  7   |  April    |  << a,April    
+-----+------+-----+-----+

You'll need a table with a list of months (eg month_id, month_name). You can then do something like this:

SELECT t.*, m.* FROM months m LEFT JOIN table t ON m.month_id = t.month_id

Otherwise, there's no way for the query to know that there's such a thing as 'March'.

在sql中使您的查询如下:

SELECT * FROM table WHERE (value='0' OR value='yourcondition') AND..

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