顯示包含「mysql」標籤的文章。顯示所有文章
顯示包含「mysql」標籤的文章。顯示所有文章

MySQL ~ order by field DESC but ASC

當想要ORDER BY `date` DESC

可是在他輸出的時候卻又要`date` ASC

作法就是

子查詢~

SELECT * FROM
(SELECT * FROM xxx ORDER BY `date` DESC LIMIT 10) as tbl
ORDER BY `date` ASC


MySQL ~ get this weekend date

this example is show how to get this week's saturday and next week's sunday.....


2010-09-15 is wednesday
SQL
select * FROM events WHERE (week(event_date) = WEEK('2010-09-15') AND DAYOFweek(event_date) = 7) OR (week(event_date) = (WEEK('2010-09-15') +1) AND DAYOFweek(event_date) = 1)


Result
2010-09-18
2010-09-19

----------------------------------------------------------------------------------------

2010-09-18 is saturday
SQL
select * FROM events WHERE (week(event_date) = WEEK('2010-09-18') AND DAYOFweek(event_date) = 7) OR (week(event_date) = (WEEK('2010-09-18') +1) AND DAYOFweek(event_date) = 1)

Result
2010-09-18
2010-09-19

----------------------------------------------------------------------------------------

get current date's weekend
SQL
select * FROM events WHERE (week(event_date) = WEEK(CURDATE()) AND DAYOFweek(event_date) = 7) OR (week(event_date) = (WEEK(CURDATE()) +1) AND DAYOFweek(event_date) = 1)

Result
2010-09-18
2010-09-19

----------------------------------------------------------------------------------------

reference
http://www.webmasterworld.com/forum88/4585.htm

MySQL ~ ignore case

$xxx = strtolower('Bitty');

$sql = "SELECT xxxxxxxxxxxxxx FROM users WHERE lower(firstname) LIKE '%".$xxx."%'";

reference
http://bytes.com/topic/mysql/answers/689805-ignore-case-when-performing-search-mysql

MySQL ~ add Days ~ increase Days

INSERT INTO `qqqqqq` (`aaaaaaa`, `bbbbbb`, `ccccc`) VALUES ('1231313213', NOW()+INTERVAL 3 DAY, '112321')

http://dev.mysql.com/doc/refman/5.0/en/datetime.html

PHP ~ read sql file to import database

這個程式是用來讀取local上的檔案來匯入資料庫

只適用單列查詢XD

所以我的作法是先匯入所有table的結構

在匯出data成insert語法成檔案~~~~~在執行程式匯入

---------------------------------------------------------------------------------------------------------------------

function db_connect(){
$link = mysqli_connect('localhost','root','12345678','dbname');
mysqli_query($link, "SET CHARACTER SET utf8");
return $link;
}

function db_query($sql){
return mysqli_query($GLOBALS['link'], $sql);
}

$GLOBALS['link'] = db_connect();

$handle = fopen("database.sql", "r");

while(!feof($handle))
{
db_query(fgets($handle));
}

fclose($handle);

MySQL ~ check identical email

SELECT letter_email
FROM `newsletter_subscribers`
GROUP BY letter_email
HAVING COUNT(*) > 1

要感謝張睪@@

一開始我的用法是WHERE說.......一直出錯問了張搞才知道要用having~XD

由於之前老外寫的程式沒有check信箱有沒有訂閱過

所以造成資料庫有相同的email


用這SQL查出數量大於1的email後再把他刪除.........我是手動的........

因為我不會配DELETE語法~~~~而且我也怕SQL沒下好刪到不該刪的資料XD

MySQL ~ COUNT(*) and GROUP BY year and month

SQL

SELECT COUNT(*) AS count, YEAR(date) AS year, MONTH(date) AS month FROM news GROUP BY YEAR(date), MONTH(date) ORDER BY year DESC


Result
count year month
4 2010 1
1 2010 2
4 2010 3
6 2010 4
6 2010 5
1 2009 3
3 2009 5
6 2009 6
4 2009 7
1 2009 8
4 2009 9
9 2009 10
2 2009 11
4 2009 12
1 2008 1
1 2008 3
1 2008 4
1 2008 5
5 2008 6
1 2008 7
8 2008 8
3 2008 9
3 2008 10
2 2008 11
3 2008 12
2 2007 3

MySQL ~ Querying for locations by defined radius

switch ($unit)
{
  /*** miles ***/
  case 'm':
   $unit = 3963;
   break;
  /*** nautical miles ***/
  case 'n':
   $unit = 3444;
   break;
  default:
   /*** kilometers ***/
   $unit = 6371;
}
$sql = "SELECT name, club_id, latitude,longitude, ( ". $unit . " * ACOS( COS( RADIANS( " . $latitude. ") ) * COS( RADIANS( latitude ) ) * COS( RADIANS( longitude ) - RADIANS( ". $longitude. ") ) + SIN( RADIANS(".$latitude.") ) * SIN( RADIANS( latitude ) ) ) ) AS distance FROM clubs HAVING distance < ".$distance." ORDER BY distance";

MySQL Error: 1194 ~ xxx is marked as crashed and should be repaired

if u got this message ~ try to repair your tables~

this site gives a cool explanation and procedure~
http://paulstamatiou.com/how-to-quickie-repair-mysql-tables-in-phpmyadmin


我昨天發生這問題= =

可是發現程式裡的SQL查詢是正確的說.....所以只好先把warning message隱藏

免得其他人來看網站......看到錯誤訊息就搞笑了XD

而今天找到這文章~~~~~

試著去修理MySQL~~~~錯誤訊息就消失了~~~cool~~~~~~~

SQL ~ DISTINCT two columns

if u want distinct a and b ~ user GROUP BY

SELECT a, b, c FROM Table
GROUP BY a, b

http://stackoverflow.com/questions/192924/sql-distinct-for-2-fields-in-a-database

MSSQL ~ INSERT with SELECT

SELECT Query
SELECT a, b ,c FROM Table

INSERT
INSERT INTO Table2(a, b, c)

INSERT with SELECT query~
INSERT INTO Table2(a, b, c)
SELECT a, b ,c FROM Table

http://www.1keydata.com/tw/sql/sqlinsert.html

MySQL ~ 取得距離現在一天以上的資料

假如我要取得一筆存取時間有一天以上的資料~~~!?

例如人家今天存了這筆資料~~~時間是12/15

在今天就是12/15~~都抓不到這筆~~~~~直到到了12/16才抓得到


SQL語法~

SELECT url FROM urls WHERE (CURDATE()-1) >= createdDate 


如果要順便隨機取 + 只取一筆

SELECT url FROM urls WHERE (CURDATE()-1) >= createdDate ORDER BY RAND() LIMIT 1

這邊的寫法是只有日期~~~~如果要更輕確的算一天的時間

應該是要用timestamp~~~我還沒試過XD

PHP ~ SQL Injection

這方法是參考張睪的方法XD

是用Dreamweaver內建的函式~~

function GetSQLValueString($theValue, $theType, $theDefinedValue = "", $theNotDefinedValue = "") 
{
  if (PHP_VERSION < 6) {
    $theValue = get_magic_quotes_gpc() ? stripslashes($theValue) : $theValue;
  }

  $theValue = function_exists("mysql_real_escape_string") ? mysql_real_escape_string($theValue) : mysql_escape_string($theValue);

  switch ($theType) {
    case "text":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;    
    case "long":
    case "int":
      $theValue = ($theValue != "") ? intval($theValue) : "NULL";
      break;
    case "double":
      $theValue = ($theValue != "") ? doubleval($theValue) : "NULL";
      break;
    case "date":
      $theValue = ($theValue != "") ? "'" . $theValue . "'" : "NULL";
      break;
    case "defined":
      $theValue = ($theValue != "") ? $theDefinedValue : $theNotDefinedValue;
      break;
  }
  return $theValue;
}


SQL的查詢寫法

$insertSQL = sprintf("INSERT INTO users (id, name, `level`, username, password, recommend, identification) VALUES (%s, %s, %s, %s, %s, %s, %s)",
                       GetSQLValueString($_POST['id'], "int"),
                       GetSQLValueString($_POST['name'], "text"),
                       GetSQLValueString($_POST['level'], "text"),
                       GetSQLValueString($_POST['username'], "text"),
                       GetSQLValueString($_POST['password'], "text"),
                       GetSQLValueString($_POST['recommend'], "int"),
                       GetSQLValueString($_POST['identification'], "text"));

我是覺得這樣寫還蠻簡易~~~

想當年我是用一種鳥方法把所有POST的東西都過濾

$link = db_connect();
$myFilter = new InputFilter();
$_POST = $myFilter->safeSQL($_POST, $link);
while (list($key, $value) = each( $_POST)) {
$_POST[$key] = mysql_real_escape_string($value);
}
while (list($key, $value) = each( $_GET)) {
$_GET[$key] = mysql_real_escape_string($value);
}

InputFilter這個物件是我在網路上抓的~
http://www.phpclasses.org/browse/package/2189.html

MySQL 取得指定時間內的資料

這段SQL語法是取popular資料裡的date欄位~~~與現在時間差15分鐘內的資料
SELECT * FROM `popular` WHERE UNIX_TIMESTAMP(`date`) > (UNIX_TIMESTAMP(NOW()) - 900)


如果想取總數~~~~~~使用DISTINCT ip配COUNT~~~就是15分鐘內有多少人~~
SELECT COUNT(DISTINCT(`ip`)) as xx FROM `popular` WHERE UNIX_TIMESTAMP(`date`) > (UNIX_TIMESTAMP(NOW()) - 900)


我的做法是把它轉UNIX_TIMESTAMP

再把它剪去900~~~~就是15分鐘~900秒

不知道這方法好不好~~~~~總之可行就是了XD

PHP ~ CSV檔匯入至MySQL

參考看看囉~~~~~~~~

主要是使用 fgetcsv這個函式取出來~

只是在之前要先知道資料庫長甚麼樣子= =

$csv_file = "test3.csv";
$fp = fopen($csv_file,"r");
$filesize = filesize($csv_file);

while( $rows = fgetcsv($fp,$filesize)){
$sql = "INSERT INTO `ggyy` ( `id` , `serial_number` , `password` ) VALUES ( NULL , '".$rows[0]."', '".$rows[1]."' );";
db_query($sql);
}

MySQL ~ 取得網頁總瀏覽人數

我的寫法是配合子查詢的.........不知道有沒有更好的寫法= ="

這個是取得當日瀏覽數的語法
SELECT COUNT(DISTINCT(`ip`)) as xx FROM `popular` WHERE DATE(`date`) = DATE(NOW())

改成這樣~~~她會把每天~~~當日的總瀏覽數變成xx欄位~~~ 一個一個輸出
SELECT COUNT(DISTINCT(`ip`)) as xx FROM `popular` GROUP BY DATE(`date`)

再把它變成子查詢~~~~外面用SUM函式把xx加總起來
SELECT SUM(xx) FROM (SELECT COUNT(DISTINCT(`ip`)) as xx, date FROM `popular` GROUP BY DATE(`date`) ) as xx

跑出來的東西就是總瀏覽數~~~~

可以參考MySQL的當日瀏覽數做法XD
http://bittyferrari.blogspot.com/2008/07/mysql.html

MySQL 當日人氣~當日瀏覽數做法

我現在做的這網頁........說要有當日人氣顯示...........

所以我設了一個資料表專門紀錄人家來網站的參數

共紀錄三個東西~~~~IP, 時間, 瀏覽的網頁

欄位名稱就是ip,date,page

然後要取得今天的瀏覽人數是多少.................語法這樣下


SELECT * FROM `popular` WHERE DATE(`date`) = DATE(NOW())
這語法會取得所有今天瀏覽產生的資料

在改成這個~
SELECT DISTINCT(`ip`) FROM `popular` WHERE DATE(`date`) = DATE(NOW())
會取得所有今天有瀏覽的IP

在改成這樣~~
SELECT COUNT(DISTINCT(`ip`)) as xx FROM `popular` WHERE DATE(`date`) = DATE(NOW())
就會取得出今天的瀏覽人數~~~欄位名稱叫xx


可以上MySQL官網找Date的文件~~
http://dev.mysql.com/doc/refman/5.0/en/date-and-time-functions.html

MySql 隨機排序輸出 ~ ORDER BY RAND()

如果想隨機排序輸出某某資料~~~~~

就用 ORDER BY RAND()

SELECT * FROM products WHERE category_id = '3' ORDER BY RAND() LIMIT 3

這樣就是隨機輸出~~~~3個

MySQL的 DISTINCT 與 COUNT

如果要用DISTINCT~~~

並且得知取得多少個欄位

要這樣打

SELECT COUNT( DISTINCT name) as xx FROM products

這樣取出來的xx就是DISTINCT過後的總數

Client does not support authentication protocol

如果您的php連接資料庫的函式是

mysql

那妳在連線 MySQL 4.1.1 版本或是更高版本~~會出現錯誤訊息
Client does not support authentication protocol requested
by server; consider upgrading MySQL client

所以要改用

mysqli

來連線~~~~~~~~可是如果您的php沒有支援到mysqli

就查詢以下指令

SET PASSWORD FOR 'some_user'@'some_host' = OLD_PASSWORD('newpwd');

UPDATE mysql.user SET Password = OLD_PASSWORD('newpwd') WHERE Host = 'some_host'
AND User = 'some_user';


FLUSH PRIVILEGES;
查詢這三段SQL語法之後~~~妳就可以用該帳號密碼登入4.11版本以上的Mysql經由php的mysql函式


會搞到這東西~~~因為研發處的網頁........@@

資料來源: http://dev.mysql.com/doc/refman/5.0/en/old-client.html