0
$query = mysql_query(SELECT * FROM test WHERE SUBSTRING(date,0,4)="1392") //for example 1392
echo query['name'];

我想得到 4 个第一个字符并检查它是否与 1392 相等。但它返回 1054 我的列名类型是 varchar,我对此一无所知。

4

3 回答 3

2

MySQL 从 1 开始计数 char,而不是从 0 开始作为 php。尝试

SUBSTRING(date,1,4)="1392"

或者如果你想要年份

YEAR(date)="1392"

http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_substring

编辑测试示例

CREATE TABLE babak (name VARCHAR(20) NOT NULL, date VARCHAR(10) NOT NULL);
INSERT INTO babak SELECT 'test', '1391/11/11';
INSERT INTO babak SELECT 'correct', '1932/11/11';

SELECT * FROM babak WHERE YEAR(date) = 1932;
+---------+------------+
| name    | date       |
+---------+------------+
| correct | 1932/11/11 |
+---------+------------+

SELECT * FROM babak WHERE SUBSTRING(date, 1, 4) = 1932;
+---------+------------+
| name    | date       |
+---------+------------+
| correct | 1932/11/11 |
+---------+------------+
于 2012-07-07T09:46:05.073 回答
1

所以你的日期是varchar格式的yyyy/MM/dd,试试这个:

SELECT   *
  FROM   test 
 WHERE   SUBSTRING(`date`,1,4) = '1932'

单击此处进行演示

于 2012-07-07T10:04:00.233 回答
0

mysql_query 只返回一个资源,您需要使用该资源来获取结果

$resource = mysql_query('SELECT * FROM test WHERE SUBSTRING(date,1,4)="1392"')
$result = mysql_fetch_assoc($resource);
echo $result['name'];
于 2012-07-07T10:00:39.113 回答