773

Table of Contents - texnologiya.az Table of Contents About this book MySQL ... Unicode (3 questions) Import (3 questions) ... category you can easily flip through the questions contained

Embed Size (px)

Citation preview

  • TableofContentsAboutthisbookMySQL(76questions)Database(44questions)InnoDB(15questions)ForeignKeys(13questions)Osx(11questions)JOIN(11questions)RubyOnRails(11questions)Performance(10questions)Select(10questions)DateTime(10questions)Mysqldump(10questions)Python(8questions)Indexing(8questions)PDO(8questions)DatabaseDesign(8questions)Types(8questions)CommandLine(7questions)Ruby(6questions)PostgreSQL(6questions)PhpMyAdmin(6questions)SqlOrderBy(6questions)PrimaryKey(6questions)SQLUPDATE(6questions)Java(5questions)Linux(5questions)Insert(5questions)MySQLWorkbench(5questions)Table(4questions)Windows(4questions)CSV(4questions)Migration(4questions)Django(4questions)Schema(4questions)GROUPBY(4questions)Date(4questions)Collation(4questions)Utf8(4questions)GreatestNPerGroup(4questions)C#(3questions)SQLServer(3questions)SQLite(3questions)

  • Security(3questions)String(3questions)Unicode(3questions)Import(3questions)Logging(3questions)Homebrew(3questions)Varchar(3questions)Timestamp(3questions)FullTextSearch(3questions)StoredProcedures(3questions)MysqlManagement(3questions)SQLInjection(3questions)Key(3questions)ALTERTABLE(3questions)Order(3questions)Duplicates(3questions)AutoIncrement(3questions)GroupConcat(3questions)Sqldatatypes(3questions)MysqlError1025(3questions)MysqlError1045(3questions)RubyOnRails3(3questions)JavaScript(2questions)Sockets(2questions)Arrays(2questions)Optimization(2questions)ORM(2questions)Ddl(2questions)Replace(2questions)Concatenation(2questions)Upsert(2questions)Mysql5(2questions)RowNumber(2questions)Max(2questions)CaseSensitive(2questions)BETWEEN(2questions)AmazonEC2(2questions)CompositeKey(2questions)Alter(2questions)DuplicateRemoval(2questions)WhereClause(2questions)Rank(2questions)Processlist(2questions)DeleteRow(2questions)Node.Js(2questions)MysqlError1093(2questions)

  • MysqlError1293(2questions)OsxYosemite(2questions)Regex(1question)GIS(1question)Math(1question)Variables(1question)Syntax(1question)Statistics(1question)Double(1question)Replication(1question)Null(1question)Multilingual(1question)Merge(1question)Configuration(1question)UUID(1question)TimeZone(1question)Conditional(1question)Monitoring(1question)JSON(1question)Caching(1question)Integer(1question)Deadlock(1question)PIVOT(1question)VirtualBox(1question)Timeout(1question)Controller(1question)Transactions(1question)PivotTable(1question)InsertId(1question)Operators(1question)InformationSchema(1question)Overhead(1question)CPUUsage(1question)CharacterEncoding(1question)Sha256(1question)AccessDenied(1question)PasswordProtection(1question)GreatCircle(1question)Deprecated(1question)UniqueKey(1question)PolymorphicAssociations(1question)UnixTimestamp(1question)MysqlError1054(1question)MariaDB(1question)MysqlError1248(1question)Doctrine2(1question)

  • InsertSelect(1question)INTOOUTFILE(1question)SQLINSERT(1question)MysqlError1170(1question)MysqlError1130(1question)MySQLError2006(1question)Copyright

  • AboutthisbookThisbookhasbeendividedintocategorieswhereeachquestionbelongstooneormorecategories.Thecategoriesarelistedbasedonhowmanyquestionstheyhave;thequestionappearsinthemostpopularcategory.Everythingislinkedinternally,sowhenbrowsingacategoryyoucaneasilyflipthroughthequestionscontainedwithinit.Wherepossiblelinkswithinquestionsandanswerslinktoappropriateplaceswithininthebook.Ifalinkdoesntlinktowithinthebook,thenitgetsaspecialicon,likethis .

    http://www.example.com

  • MySQLSkiptoquestions,

    Wikibyuserpaul-dixon

    MySQL isanOpenSourcerdbms (RelationalDatabaseManagementSystem)thatrunsasaserverprovidingmulti-useraccesstoanumberofdatabases.ItssourcecodeisavailableundertheGNU (GeneralPublicLicense).

    MySQL offersstandarddatabasedriverconnectivityforusingMySQLwithapplicationsandtoolsthatarecompatiblewithindustrystandardsodbc andjdbc .

    Howtoaskagoodandanswerablequestion

    Pleaseseethispost:TipsforaskingagoodStructuredQueryLanguage(SQL)questiontogetTipsonhowtoaskaquestionaboutMySQL-followingsomeofthosestepswillhelppeopletohelpyousolveyourproblem.

    Pronunciation

    Officiallyitis/maskjul/(MyS-Q-L),butisoftenpronounced/masikwl/(MySequel).

    LatestVersion:5.7.11 releasedon2016-02-05.

    Example

    SELECT*FROMusersORDERBYName

    Resources

    OfficialhomepageOfficialblogMySQLDeveloperZoneMySQLdocumentationPlanetMySQLSQLFiddlePHPMySQLDocumentation

    MySQLTutorials

    OfficialTutorial(5.7)

    Popularquestions

    http://stackoverflow.com/u/6521https://www.mysql.comhttp://stackoverflow.com/questions/tagged/rdbmshttps://www.gnu.org/https://www.mysql.comhttp://stackoverflow.com/questions/tagged/odbchttp://stackoverflow.com/questions/tagged/jdbchttp://meta.stackoverflow.com/a/271056/3993662https://dev.mysql.com/doc/relnotes/mysql/5.7/en/news-5-7-11.htmlhttps://www.mysql.comhttps://blogs.oracle.com/MySQLhttps://dev.mysql.comhttps://dev.mysql.com/dochttp://planet.mysql.comhttp://sqlfiddle.comhttps://php.net/manual/en/set.mysqlinfo.phphttps://dev.mysql.com/doc/refman/5.7/en/tutorial.html

  • HiddenFeaturesofMySQLSQLitevsMySQLWouldyourecommendPostgreSQLoverMySQL?BestwaytopreventSQLinjectioninPHP?HowtodoaregularexpressionreplaceinMySQL?HowdoyousetadefaultvalueforaMySQLDatetimecolumn?

    Popularadministrationtools

    PhpMyAdminMySQLWorkbenchHeidiSQLNavicatRazorSQL

    ChatRoom

    StackOverflowchatroomforMySQL

    Relatedtags

    databasemysqlimysqldumpmysql-connectormysql2mysql5mysql-real-escape-stringmysql-managementmysql-error-1005mysql-error-1045mysql-error-1054mysql-error-1062mysql-error-1064mysql-connectmysqlldmysqlimportmysql-managementmysql-workbench

    https://stackoverflow.com/questions/368858/hidden-features-of-mysqlhttps://stackoverflow.com/questions/3630/sqlite-vs-mysqlhttps://stackoverflow.com/questions/110927/do-you-recommend-postgresql-over-mysqlhttp://www.phpmyadmin.net/https://www.mysql.com/products/workbench/http://www.heidisql.com/http://www.navicat.com/http://razorsql.com/https://chat.stackoverflow.com/rooms/592/mysql-and-relational-databaseshttp://stackoverflow.com/questions/tagged/mysqlihttp://stackoverflow.com/questions/tagged/mysql-connectorhttp://stackoverflow.com/questions/tagged/mysql2http://stackoverflow.com/questions/tagged/mysql-real-escape-stringhttp://stackoverflow.com/questions/tagged/mysql-error-1005http://stackoverflow.com/questions/tagged/mysql-error-1062http://stackoverflow.com/questions/tagged/mysql-error-1064http://stackoverflow.com/questions/tagged/mysql-connecthttp://stackoverflow.com/questions/tagged/mysqlldhttp://stackoverflow.com/questions/tagged/mysqlimport

  • Questions

    Q:HowdoIretrievemyMySQLusernameandpassword?

    Tags:mysql(NextQ)

    IlostmyMySQLusernameandpassword.HowdoIretrieveit?

    Tags:mysql(NextQ)

    User:marcel-tjandraatmadja

    Answer byxenph-yan

    StoptheMySQLprocess.

    StarttheMySQLprocesswiththeskip-grant-tablesoption.

    StarttheMySQLconsoleclientwiththe-urootoption.

    Listalltheusers;SELECT*FROMmysql.user;

    Resetpassword;UPDATEmysql.userSETPassword=PASSWORD('[password]')WHEREUser='[username]';

    ButDONOTFORGETto

    StoptheMySQLprocess

    StarttheMySQLProcessnormally(i.e.withouttheskip-grant-tablesoption)

    whenyouarefinished.Otherwise,yourdatabasessecuritycouldbecompromised.

    Tags:mysql(NextQ)

    Q:HowdoIchecktoseeifavalueisanintegerinMySQL?

    Tags:mysql(PrevQ)(NextQ)

    IseethatwithinMySQLthereareCast()andConvert()functionstocreateintegersfromvalues,butisthereanywaytochecktoseeifavalueisaninteger?Somethinglikeis_int()inPHPiswhatIamlookingfor.

    Tags:mysql(PrevQ)(NextQ)

    User:craig-nakamoto

    Answer byjumpy

    http://stackoverflow.com/q/4371http://stackoverflow.com/u/131http://stackoverflow.com/q/4376http://stackoverflow.com/u/264http://stackoverflow.com/q/75704http://stackoverflow.com/u/8224http://stackoverflow.com/q/75880http://stackoverflow.com/u/9416

  • Illassumeyouwanttocheckastringvalue.OnenicewayistheREGEXPoperator,matchingthestringtoaregularexpression.SimplydoselectfieldfromtablewherefieldREGEXP'^-?[0-9]+$';

    thisisreasonablyfast.Ifyourfieldisnumeric,justtestforceil(field)=field

    instead.

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQLError1153-Gotapacketbiggerthanmax_allowed_packetbytes

    Tags:mysql(PrevQ)(NextQ)

    ImimportingaMySQLdumpandgettingthefollowingerror.$mysqlfoogetMessage();}

    (Ofcoursereplacedatabasename,usernameandpasswordabove)

    Youcanthenquerythedatabaselikethis:$result=$db->query("select*fromtablename");foreach($resultas$row){echo$row['foo']."\n";}

    Or,ifyouhavevariables:$stmt=$db->prepare("select*fromtablenamewhereid=:id");$stmt->execute(array(':id'=>42));$row=$stmt->fetch();

    Ifyouneedmultipleconnectionsopenatonce,youcansimplycreatemultipleinstancesofPDO:try{$db1=newPDO('mysql:dbname=databas1;host=127.0.0.1','username','password');$db2=newPDO('mysql:dbname=databas2;host=127.0.0.1','username','password');}catch(PDOException$ex){echo'Connectionfailed:'.$ex->getMessage();}

    Tags:mysql(PrevQ)(NextQ)

    Q:GetrecordcountsforalltablesinMySQLdatabase

    Tags:mysql(PrevQ)(NextQ)

    IsthereawaytogetthecountofrowsinalltablesinamysqldatabasewithoutrunningaSELECTcount()oneachtable?

    Cheers

    Tags:mysql(PrevQ)(NextQ)

    User:mark

    Answer byhates_SELECTSUM(TABLE_ROWS)

    http://stackoverflow.com/q/275013http://stackoverflow.com/u/18180http://docs.php.net/manual/en/book.pdo.phphttp://stackoverflow.com/q/286039http://stackoverflow.com/u/37204http://stackoverflow.com/q/286048http://stackoverflow.com/u/3410

  • FROMINFORMATION_SCHEMA.TABLESWHERETABLE_SCHEMA='{your_db}';

    Notefromthedocsthough:ForInnoDBtables,therowcountisonlyaroughestimateusedinSQLoptimization.YoullneedtouseCOUNT(*)forexactcounts(whichismoreexpensive).

    Answer bygpojd

    YoucanprobablyputsomethingtogetherwithTablestable .Iveneverdoneit,butitlookslikeithasacolumnfor*TABLE_ROWS*andoneforTABLENAME.

    Togetrowspertable,youcanuseaquerylikethis:SELECTtable_name,table_rowsFROMINFORMATION_SCHEMA.TABLESWHERETABLE_SCHEMA='**YOURSCHEMA**';

    Answer bynathan

    Like@VenkatramananandothersIfoundINFORMATION_SCHEMA.TABLESunreliable(usingInnoDB,MySQL5.1.44),givingdifferentrowcountseachtimeIrunitevenonquiescedtables.Heresarelativelyhacky(butflexible/adaptable)wayofgeneratingabigSQLstatementyoucanpasteintoanewquery,withoutinstallingRubygemsandstuff.SkipcodeblockSELECTCONCAT('SELECT"',table_name,'"AStable_name,COUNT(*)ASexact_row_countFROM`',table_schema,'`.`',table_name,'`UNION')FROMINFORMATION_SCHEMA.TABLESWHEREtable_schema='**my_schema**';

    Itproducesoutputlikethis:SELECT"func"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.funcUNIONSELECT"general_log"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.general_logUNIONSELECT"help_category"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.help_categoryUNIONSELECT"help_keyword"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.help_keywordUNIONSELECT"help_relation"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.help_relationUNIONSELECT"help_topic"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.help_topicUNIONSELECT"host"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.hostUNIONSELECT"ndb_binlog_index"AStable_name,COUNT(*)ASexact_row_countFROMmy_schema.ndb_binlog_indexUNION

    CopyandpasteexceptforthelastUNIONtogetniceoutputlike,Skipcodeblock+------------------+-----------------+|table_name|exact_row_count|+------------------+-----------------+|func|0||general_log|0||help_category|37||help_keyword|450||help_relation|990||help_topic|504||host|0||ndb_binlog_index|0|+------------------+-----------------+

    http://stackoverflow.com/q/286047http://stackoverflow.com/u/28071http://dev.mysql.com/doc/refman/5.0/en/tables-table.htmlhttp://stackoverflow.com/q/8690288http://stackoverflow.com/u/71650

  • 8rowsinset(0.01sec)

    Tags:mysql(PrevQ)(NextQ)

  • Q:HowcanItellwhenaMySQLtablewaslastupdated?

    Tags:mysql(PrevQ)(NextQ)

    Inthefooterofmypage,Iwouldliketoaddsomethinglikelastupdatedthexx/xx/200xwiththisdatebeingthelasttimeacertainmySQLtablehasbeenupdated.

    Whatisthebestwaytodothat?Isthereafunctiontoretrievethelastupdateddate?ShouldIaccesstothedatabaseeverytimeIneedthisvalue?

    Tags:mysql(PrevQ)(NextQ)

    User:rage

    Answer byalnitak

    InlaterversionsofMySQLyoucanusetheinformation_schemadatabasetotellyouwhenanothertablewasupdated:SELECTUPDATE_TIMEFROMinformation_schema.tablesWHERETABLE_SCHEMA='dbname'ANDTABLE_NAME='tabname'

    Thisdoesofcoursemeanopeningaconnectiontothedatabase.

    AnalternativeoptionwouldbetotouchaparticularfilewhenevertheMySQLtableisupdated:

    Ondatabaseupdates:

    OpenyourtimestampfileinO_RDRWmodecloseitagain

    oralternatively

    usetouch() ,thePHPequivalentoftheutimes()function,tochangethefiletimestamp.

    Onpagedisplay:

    usestat()toreadbackthefilemodificationtime.

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQL/SQL:GroupbydateonlyonaDatetimecolumn

    Tags:mysql(PrevQ)(NextQ)

    Havingatablewithacolumnlike:mydateDATETIME

    http://stackoverflow.com/q/307438http://stackoverflow.com/u/39474http://stackoverflow.com/q/307488http://stackoverflow.com/u/6782http://us3.php.net/manual/en/function.touch.phphttp://stackoverflow.com/q/366603

  • Ihaveaquerysuchas:SELECTSUM(foo),mydateFROMa_tableGROUPBYa_table.mydate;

    Thiswillgroupbythefulldatetime,includinghoursandminutes.Iwishtomakethegroupby,onlybythedateYYYY/MM/DDnotbytheYYYY/MM/DD/HH/mm.

    Anyoneknowhowtodothis?Icanstilldoit(asIamatm),dynamicallyinmycode,butImcleaningtrashcodeandthiscanbemadethroughtheSQLIjustcantfindouthow:(.

    Tags:mysql(PrevQ)(NextQ)

    User:fmsf

    Answer bymichael-haren

    Castthedatetimetoadate,thenGROUPBYusingthissyntax:SELECTSUM(foo),DATE(mydate)FROMa_tableGROUPBYDATE(a_table.mydate);

    OryoucanGROUPBYthealiasas@orlandu63suggested:SELECTSUM(foo),DATE(mydate)DateOnlyFROMa_tableGROUPBYDateOnly;

    ThoughIdontthinkitllmakeanydifferencetoperformance,itisalittleclearer.

    Tags:mysql(PrevQ)(NextQ)

    Q:SQL-findrecordsfromonetablewhichdontexistinanother

    Tags:mysql(PrevQ)(NextQ)

    IvegotthefollowingtwoSQLtables(inMySQL):SkipcodeblockPhone_book+----+------+--------------+|id|name|phone_number|+----+------+--------------+|1|John|111111111111|+----+------+--------------+|2|Jane|222222222222|+----+------+--------------+

    Call+----+------+--------------+|id|date|phone_number|+----+------+--------------+|1|0945|111111111111|+----+------+--------------+|2|0950|222222222222|+----+------+--------------+|3|1045|333333333333|+----+------+--------------+

    HowdoIfindoutwhichcallsweremadebypeoplewhosephone_numberisnotinthePhone_book?Thedesiredoutputwouldbe:Call+----+------+--------------+|id|date|phone_number|+----+------+--------------+

    http://stackoverflow.com/u/26004http://stackoverflow.com/q/366610http://stackoverflow.com/u/29http://stackoverflow.com/q/367863

  • |3|1045|333333333333|+----+------+--------------+

    Anyhelpwouldbemuchappreciated.

    Tags:mysql(PrevQ)(NextQ)

    User:philip-morton

    Answer byalnitak

    Theresseveraldifferentwaysofdoingthis,withvaryingefficiency,dependingonhowgoodyourqueryoptimiseris,andtherelativesizeofyourtwotables:

    Thisistheshorteststatement,andmaybequickestifyourphonebookisveryshort:SELECT*FROMCallWHEREphone_numberNOTIN(SELECTphone_numberFROMPhone_book)

    alternatively(thankstoAlterlife )SELECT*FROMCallWHERENOTEXISTS(SELECT*FROMPhone_bookWHEREPhone_book.phone_number=Call.phone_number)

    or(thankstoKieran )SELECT*FROMCallLEFTOUTERJOINPhone_BookON(Call.phone_number=Phone_book.phone_number)WHEREPhone_book.phone_numberISNULL

    (ignoringthat,asothershavesaid,itsnormallybesttoselectjustthecolumnsyouwant,not*)

    Answer bywoprSELECTCall.ID,Call.date,Call.phone_numberFROMCallLEFTOUTERJOINPhone_BookON(Call.phone_number=Phone_book.phone_number)WHEREPhone_book.phone_numberISNULL

    Shouldremovethesubquery,allowingthequeryoptimisertoworkitsmagic.

    Also,avoidSELECT*becauseitcanbreakyourcodeifsomeonealterstheunderlyingtablesorviews(anditsinefficient).

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQLvsMySQLiwhenusingPHP

    Tags:mysql(PrevQ)(NextQ)

    Whichisbetter,MySQLorMySQLi?Andwhy?WhichshouldIuse?

    http://stackoverflow.com/u/21709http://stackoverflow.com/q/367865http://stackoverflow.com/u/6782http://stackoverflow.com/users/36848/alterlifehttp://stackoverflow.com/users/46255/kieranhttp://stackoverflow.com/q/368123http://stackoverflow.com/u/46255http://stackoverflow.com/q/548986

  • Imeanbetternotjustintermsofperformance,butanyotherrelevantfeature.

    Tags:mysql(PrevQ)(NextQ)

    User:anand.trex

    Answer bymark-davidson

    IfyouhavealookatMySQLImprovedExtensionOverview ,itshouldtellyoueverythingyouneedtoknowaboutthedifferencesbetweenthetwo.

    Themainusefulfeaturesare:

    anObject-orientedinterfacesupportforpreparedstatementssupportformultiplestatementssupportfortransactionsenhanceddebuggingcapabilitiesembeddedserversupport.

    Answer bygordon

    Thereisamanualpagededicatedtohelpchoosingbetweenmysql,mysqliandPDOat

    http://php.net/manual/en/mysqlinfo.api.choosing.php andhttp://www.php.net/manual/en/mysqlinfo.library.choosing.php

    ThePHPteamrecommendsmysqliorPDO_MySQLfornewdevelopment:

    ItisrecommendedtouseeitherthemysqliorPDO_MySQLextensions.Itisnotrecommendedtousetheoldmysqlextensionfornewdevelopment.Adetailedfeaturecomparisonmatrixisprovidedbelow.Theoverallperformanceofallthreeextensionsisconsideredtobeaboutthesame.AlthoughtheperformanceoftheextensioncontributesonlyafractionofthetotalruntimeofaPHPwebrequest.Often,theimpactisaslowas0.1%.

    ThepagealsohasafeaturematrixcomparingtheextensionAPIs.ThemaindifferencesbetweenmysqliandmysqlAPIareasfollows:SkipcodeblockmysqlimysqlDevelopmentStatusActiveMaintenanceonlyLifecycleActiveLongTermDeprecationAnnounced*RecommendedYesNoOOPAPIYesNoAsynchronousQueriesYesNoServer-SidePrep.StatementsYesNoStoredProceduresYesNoMultipleStatementsYesNoTransactionsYesNoMySQL5.1+functionalityYesNo

    *http://news.php.net/php.internals/53799

    Thereisanadditionalfeaturematrixcomparingthelibraries(newmysqlndversus

    http://stackoverflow.com/u/12649http://stackoverflow.com/q/549000http://stackoverflow.com/u/50866http://php.net/manual/en/mysqli.overview.phphttp://stackoverflow.com/q/8891836http://stackoverflow.com/u/208809http://php.net/manual/en/mysqlinfo.api.choosing.phphttp://www.php.net/manual/en/mysqlinfo.library.choosing.phphttp://news.php.net/php.internals/53799

  • libmysql)at

    http://www.php.net/manual/en/mysqlinfo.library.choosing.php

    andaverythoroughblogarticleat

    http://blog.ulf-wendel.de/2012/php-mysql-why-to-upgrade-extmysql/

    Tags:mysql(PrevQ)(NextQ)

    Q:Searchforalloccurrencesofastringinamysqldatabase

    Tags:mysql(PrevQ)(NextQ)

    Imtryingtofigureouthowtolocatealloccurrencesofaurlinadatabase.Iwanttosearchalltablesandallfields.ButIhavenoideawheretostartorifitsevenpossible.

    Tags:mysql(PrevQ)(NextQ)

    User:gregh

    Answer bypaolo-bergantino

    Asimplesolutionwouldbedoingsomethinglikethis:mysqldump-umyuser--no-create-infodatabasename>myfile.sql

    Thenyoucanjustdoafindonmyfile.sqlfortheURLyouwant.

    Answer bya.-googler

    OldpostIknow,butforothersthatfindthisviaGooglelikeIdid,ifyouhavephpmyadmininstalled,ithasaglobalsearchfeature.

    Tags:mysql(PrevQ)(NextQ)

    Q:Add2hourstocurrenttimeinMySQL?

    Tags:mysql(PrevQ)(NextQ)

    WhichisthevalidsyntaxofthisqueryinMySQL?SELECT*FROMcoursesWHERE(now()+2hours)>start_time

    *note:start_timeisafieldofcoursestable*

    Tags:mysql(PrevQ)(NextQ)

    User:ei-maung

    Answer byglavi

    http://www.php.net/manual/en/mysqlinfo.library.choosing.phphttp://blog.ulf-wendel.de/2012/php-mysql-why-to-upgrade-extmysql/http://stackoverflow.com/q/562457http://stackoverflow.com/u/2687http://stackoverflow.com/q/562501http://stackoverflow.com/u/16417http://stackoverflow.com/q/7392555http://stackoverflow.com/u/941177http://stackoverflow.com/q/589652http://stackoverflow.com/u/22962http://stackoverflow.com/q/589668http://stackoverflow.com/u/67332

  • SELECT*FROMcoursesWHEREDATE_ADD(NOW(),INTERVAL2HOUR)>start_time

    SeeDateandTimeFunctions forotherdate/timemanipulation.

    Tags:mysql(PrevQ)(NextQ)

    Q:SearchinallfieldsfromeverytableofaMySQLdatabase

    Tags:mysql(PrevQ)(NextQ)

    IwanttosearchinallfieldsfromalltablesofaMySQLdatabaseagivenstring,possiblyusingsyntaxas:SELECT*FROM*WHERE*LIKE'%stuff%'

    Isitpossibletodosomethinglikethis?

    Tags:mysql(PrevQ)(NextQ)

    User:rsilva

    Answer bymilhous

    Youcanpeekintotheinformation_schematable.Ithasalistofalltablesandallfieldsthatareinatable.Youcanthenrunqueriesusingtheinformationthatyouhavegottenfromthistable.

    Answer bydean-rather

    YoucoulddoanSQLDumpofthedatabase(anditsdata)thensearchthatfile.

    Answer bygreg-lyon

    IfyouhavephpMyAdmininstalleduseitsSearchfeature.

    SelectyourDBBesureyoudohaveaDBselected(i.e.notatable,otherwiseyoullgetacompletelydifferentsearchdialog)ClickSearchtabChoosethesearchtermyouwantChoosethetablestosearch

    Ihaveusedthisonupto250table/10GBdatabases(onafastserver)andtheresponsetimeisnothingshortofamazing.

    Tags:mysql(PrevQ)(NextQ)

    Q:DeletewithJoininMySQL

    http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.htmlhttp://stackoverflow.com/q/639531http://stackoverflow.com/u/2019426http://stackoverflow.com/q/639538http://stackoverflow.com/u/17712http://stackoverflow.com/q/4817152http://stackoverflow.com/u/14966http://stackoverflow.com/q/3841554http://stackoverflow.com/u/179289http://stackoverflow.com/q/652770

  • Tags:mysql(PrevQ)(NextQ)SkipcodeblockCREATETABLE`clients`(`client_id`int(11),PRIMARYKEY(`client_id`));CREATETABLE`projects`(`project_id`int(11)unsigned,`client_id`int(11)unsigned,PRIMARYKEY(`project_id`));CREATETABLE`posts`(`post_id`int(11)unsigned,`project_id`int(11)unsigned,PRIMARYKEY(`post_id`));

    InmyPHPcode,whendeletingaclient,Iwanttodeleteallprojectsposts:DELETEFROMposts

    INNERJOINprojectsONprojects.project_id=posts.project_id

    WHEREprojects.client_id=:client_id;

    Thepoststabledoesnothaveaforeignkeyclient_id,onlyproject_id.Iwanttodeletepoststhatarepostedinprojectsthathavethepassedclient_id.

    Thisisnotworkingrightnow(nopostsaredeleted).

    Tags:mysql(PrevQ)(NextQ)

    User:geekjock

    Answer byyehosef

    Youjustneedtospecifythatyouwanttodeletetheentriesfromthepoststable:DELETEpostsFROMpostsINNERJOINprojectsONprojects.project_id=posts.project_idWHEREprojects.client_id=:client_id

    EDIT:Formoreinformationyoucanseethisalternativeanswer

    Tags:mysql(PrevQ)(NextQ)

    Q:FindingduplicatevaluesinMySQL

    Tags:mysql(PrevQ)(NextQ)

    Ihaveatablewithavarcharcolumn,andIwouldliketofindalltherecordsthathaveduplicatevaluesinthiscolumn.WhatisthebestqueryIcanusetofindtheduplicates?

    Tags:mysql(PrevQ)(NextQ)

    User:jon-tackabury

    http://stackoverflow.com/u/74980http://stackoverflow.com/q/4192849http://stackoverflow.com/u/214545http://stackoverflow.com/a/29204958/214545http://stackoverflow.com/q/688549http://stackoverflow.com/u/343

  • Answer bylevik

    DoaSELECTwithaGROUPBYclause.Letssaynameisthecolumnyouwanttofindduplicatesin:SELECTname,COUNT(*)cFROMtableGROUPBYnameHAVINGc>1;

    Thiswillreturnaresultwiththenamevalueinthefirstcolumn,andacountofhowmanytimesthatvalueappearsinthesecond.

    Answer bymaxyfcSELECTvarchar_colFROMtableGROUPBYvarchar_colHAVINGcount(*)>1;

    Answer byquassnoiSELECT*FROMmytablemtoWHEREEXISTS(SELECT1FROMmytablemtiWHEREmti.varchar_column=mto.varchar_columnLIMIT1,1)

    Thisqueryreturnscompleterecords,notjustdistinctvarchar_columns.

    ThisquerydoesntuseCOUNT(*).Iftherearelotsofduplicates,COUNT(*)isexpensive,andyoudontneedthewholeCOUNT(*),youjustneedtoknowiftherearetworowswithsamevalue.

    Havinganindexonvarchar_columnwill,ofcourse,speedupthisquerygreatly.

    Tags:mysql(PrevQ)(NextQ)

    Q:PHP/MySQLinsertrowthengetid

    Tags:mysql(PrevQ)(NextQ)

    TheidfieldofmytableautoincreaseswhenIinsertarow.IwanttoinsertarowandthengetthatID.

    IwoulddoitjustasIsaidit,butisthereawayIcandoitwithoutworryingaboutthetimebetweeninsertingtherowandgettingtheid?

    IknowIcanquerythedatabasefortherowthatmatchestheinformationthatwasentered,butthereisahighchangetherewillbeduplicates,withtheonlydifferencebeingtheid.

    Tags:mysql(PrevQ)(NextQ)

    User:hintswen

    Answer bycletus

    http://stackoverflow.com/q/688551http://stackoverflow.com/u/4465http://stackoverflow.com/q/688560http://stackoverflow.com/u/72990http://stackoverflow.com/q/689294http://stackoverflow.com/u/55159http://stackoverflow.com/q/897356http://stackoverflow.com/u/51310http://stackoverflow.com/q/897361http://stackoverflow.com/u/18393

  • mysqli_query("INSERTINTOmytable(1,2,3,'blah')");$id=mysqli_insert_id();

    Seemysqli_insert_id() .

    Whateveryoudo,dontinsertandthendoaSELECTMAX(id)FROMmytable.Likeyousay,itsaraceconditionandtheresnoneed.mysqli_insert_id()alreadyhasthisfunctionality.

    Tags:mysql(PrevQ)(NextQ)

    Q:HowtogetdatabasestructureinMySQLviaquery

    Tags:mysql(PrevQ)(NextQ)

    IsitpossibletosomehowgetstructureofMySQLdatabase,orjustsometablewithsimplequery?

    Oristhereanotherway,howcanIdoit?

    Tags:mysql(PrevQ)(NextQ)

    User:jakub-arnold

    Answer bybill-the-lizard

    IthinkthatwhatyoureafterisDESCRIBEDESCRIBEtable;

    YoucanalsouseSHOWTABLESSHOWTABLES;

    togetalistofthetablesinyourdatabase.

    Answer byeemeli-kantola

    TogetthewholedatabasestructureasasetofCREATETABLE statements,usemysqldump :mysqldumpdatabase_name--compact--no-data

    Forsingletables,addthetablenameafterdbnameinmysqldump.YougetthesameresultswithSQLandSHOWCREATETABLE :SHOWCREATETABLEtable;

    OrDESCRIBE ifyoupreferacolumnlisting:DESCRIBEtable;

    Tags:mysql(PrevQ)(NextQ)

    http://au.php.net/mysqli.insert_idhttp://stackoverflow.com/q/898688http://stackoverflow.com/u/72583http://stackoverflow.com/q/898710http://stackoverflow.com/u/1288http://dev.mysql.com/doc/refman/4.1/en/describe.htmlhttps://dev.mysql.com/doc/refman/5.0/en/show-tables.htmlhttp://stackoverflow.com/q/899139http://stackoverflow.com/u/94956http://dev.mysql.com/doc/refman/5.1/en/create-table.htmlhttp://dev.mysql.com/doc/refman/5.1/en/mysqldump.htmlhttp://dev.mysql.com/doc/refman/5.1/en/show-create-table.htmlhttp://dev.mysql.com/doc/refman/5.1/en/describe.html

  • Q:WhatdoestheKEYkeywordmean?

    Tags:mysql(PrevQ)(NextQ)

    Inthistabledefinition:CREATETABLEgroups(ug_main_grp_idsmallintNOTNULLdefault'0',ug_uidsmallintdefaultNULL,ug_grp_idsmallintdefaultNULL,KEY(ug_main_grp_id));

    WhatdoestheKEYkeywordmean?Itsnotaprimarykey,itsnotaforiegnkey,soisitjustanindex?Ifso,whatssospecialaboutthistypeofindexcreatedwithKEY?

    Tags:mysql(PrevQ)(NextQ)

    User:stan

    Answer bymartinodf

    Quotingfromhttp://dev.mysql.com/doc/refman/5.1/en/create-table.html{INDEX|KEY}

    SoKEYisanINDEX;)

    Tags:mysql(PrevQ)(NextQ)

    Q:Changeautoincrementstartingnumber?

    Tags:mysql(PrevQ)(NextQ)

    InMySQL,Ihaveatable,andIwanttosetthestart?auto_incrementvalueto5,not1.Isthispossibleandwhatquerystatementdoesthis?

    Tags:mysql(PrevQ)(NextQ)

    User:john-jones

    Answer bydaniel-vandersluis

    YoucanuseALTERTABLEtochangetheauto_incrementinitialvalue:ALTERTABLEtblAUTO_INCREMENT=5;

    SeetheMySQLreference formoredetails.

    Answer bycosimo

    Yes,youcanusetheALTERTABLEtAUTO_INCREMENT=42statement.However,youneedtobeawarethatthiswillcausetherebuildingofyourentiretable,atleastwithInnoDB.Ifyouhaveanalreadyexistingdatasetwithmillionsofrows,itcouldtakeaverylongtimetocomplete.

    http://stackoverflow.com/q/924265http://stackoverflow.com/q/924272http://stackoverflow.com/u/112870http://dev.mysql.com/doc/refman/5.1/en/create-table.htmlhttp://stackoverflow.com/q/970597http://stackoverflow.com/u/119894http://stackoverflow.com/q/970652http://stackoverflow.com/u/92313http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.htmlhttp://stackoverflow.com/q/12401149http://stackoverflow.com/u/11303

  • Inmyexperience,itsbettertodothefollowing:BEGINWORK;YoumayalsoneedtoaddothermandatorycolumnsandvaluesINSERTINTOt(id)VALUES(42);ROLLBACK;

    Inthisway,evenifyourerollingbackthetransaction,MySQLwillkeeptheauto-incrementvalue,andthechangewillbeappliedinstantly.

    YoucanverifythisbyissuingaSHOWCREATETABLEtstatement.Youshouldsee:>SHOWCREATETABLEt\G***************************1.row***************************Table:tCreateTable:CREATETABLE`t`(...)ENGINE=InnoDBAUTO_INCREMENT=43

    Tags:mysql(PrevQ)(NextQ)

    Q:HowdoIremoveaMySQLdatabase?

    Tags:mysql(PrevQ)(NextQ)

    Youmaynoticefrommylastquestionthataproblemcausedsomemoreproblems,ReadingMySQLmanualsinMySQLmonitor?

    Mydatabaseisnowunusablepartlyduetomyinteresttobreakthingsandmyinabilitytolookaterrormessages.IknowthatIshouldnotreuseprimarykeys,butIwouldliketousethemagainaftertheremovalofthedatabasethatIdeteriorated.So

    HowcanIcorrectlyremoveaMySQLdatabase?

    Tags:mysql(PrevQ)(NextQ)

    User:masi

    Answer byrnicholson

    FromtheMySQLprompt:mysql>DROPDATABASE;

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQLLIKEIN()?

    Tags:mysql(PrevQ)(NextQ)

    Mycurrentquerylookslikethis:SELECT*FROMfiberboxfWHEREf.fiberBoxLIKE'%1740%'ORf.fiberBoxLIKE'%1938%'ORf.fiberBoxLIKE'%1940%'

    IdidsomelookingaroundandcantfindanythingsimilartoaLIKEIN()-Ienvisionitworkinglikethis:

    http://stackoverflow.com/q/1082130http://stackoverflow.com/questions/1081399http://stackoverflow.com/u/54964http://stackoverflow.com/q/1082136http://stackoverflow.com/u/14075http://stackoverflow.com/q/1127088

  • SELECT*FROMfiberboxfWHEREf.fiberboxLIKEIN('%140%','%1938%','%1940%')

    Anyideas?AmIjustthinkingoftheproblemthewrongway-someobscurecommandIveneverseen.

    MySQL5.0.77-community-log

    Tags:mysql(PrevQ)(NextQ)

    User:michael-wales

    Answer bypaul-dixon

    AREGEXP mightbemoreefficient,butyoudhavetobenchmarkittobesure,e.g.SELECT*fromfiberboxwherefieldREGEXP'1740|1938|1940';

    Answer bydavid-carroll

    PaulDixonsanswerworkedbrilliantlyforme.Toaddtothis,herearesomethingsIobservedforthoseinterestedinusingREGEXP:

    ToAccomplishmultipleLIKEfilterswithWildcards:SELECT*FROMfiberboxWHEREfieldLIKE'%1740%'ORfieldLIKE'%1938%'ORfieldLIKE'%1940%';

    UseREGEXPAlternative:SELECT*FROMfiberboxWHEREfieldREGEXP'1740|1938|1940';

    ValueswithinREGEXPquotesandbetweenthe|(OR)operatoraretreatedaswildcards.Typically,REGEXPwillrequirewildcardexpressionssuchas(.*)1740(.*)toworkas%1740%.

    Ifyouneedmorecontroloverplacementofthewildcard,usesomeofthesevariants:

    ToAccomplishLIKEwithControlledWildcardPlacement:SELECT*FROMfiberboxWHEREfieldLIKE'1740%'ORfieldLIKE'%1938'ORfieldLIKE'%1940%test';

    Use:SELECT*FROMfiberboxWHEREfieldREGEXP'^1740|1938$|1940(.*)test';

    Placing^infrontofthevalueindicatesstartoftheline.

    Placing$afterthevalueindicatesendofline.

    Placing(.*)behavesmuchlikethe%wildcard.

    The.indicatesanysinglecharacter,exceptlinebreaks.Placing.inside()with*(.*)addsarepeatingpatternindicatinganynumberofcharacterstillendofline.

    Therearemoreefficientwaystonarrowdownspecificmatches,butthatrequiresmorereviewofRegularExpressions.NOTE:NotallregexpatternsappeartoworkinMySQL

    http://stackoverflow.com/u/2001511http://stackoverflow.com/q/1127106http://stackoverflow.com/u/6521http://dev.mysql.com/doc/refman/5.1/en/regexp.htmlhttp://stackoverflow.com/q/4808757http://stackoverflow.com/u/591080

  • statements.Youllneedtotestyourpatternsandseewhatworks.

    Finally,ToAccomplishMultipleLIKEandNOTLIKEfilters:SELECT*FROMfiberboxWHEREfieldLIKE'%1740%'ORfieldLIKE'%1938%'ORfieldNOTLIKE'%1940%'ORfieldNOTLIKE'test%'ORfield='9999';

    UseREGEXPAlternative:SELECT*FROMfiberboxWHEREfieldREGEXP'1740|1938|^9999$'ORfieldNOTREGEXP'1940|^test';

    ORMixedAlternative:SELECT*FROMfiberboxWHEREfieldREGEXP'1740|1938'ORfieldNOTREGEXP'1940|^test'ORfieldNOTLIKE'test%'ORfield='9999';

    NoticeIseparatedtheNOTsetinaseparateWHEREfilter.Iexperimentedwithusingnegatingpatterns,forwardlookingpatterns,andsoon.However,theseexpressionsdidnotappeartoyieldthedesiredresults.Inthefirstexampleabove,Iuse^9999$toindicateexactmatch.Thisallowsyoutoaddspecificmatcheswithwildcardmatchesinthesameexpression.However,youcanalsomixthesetypesofstatementsasyoucanseeinthesecondexamplelisted.

    Regardingperformance,Iransomeminortestsagainstanexistingtableandfoundnodifferencesbetweenmyvariations.However,Iimagineperformancecouldbeanissuewithbiggerdatabases,largerfields,greaterrecordcounts,andmorecomplexfilters.

    Asalways,uselogicaboveasitmakessense.

    Ifyouwanttolearnmoreaboutregularexpressions,Irecommendwww.regular-expressions.infoasagoodreferencesite.

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQL,bettertoinsertNULLoremptystring?

    Tags:mysql(PrevQ)(NextQ)

    Ihaveaformonawebsitewhichhasalotofdifferentfields.Someofthefieldsareoptionalwhilesomearemandatory.InmyDBIhaveatablewhichholdsallthesevalues,isitbetterpracticetoinsertaNULLvalueoranemptystringintotheDBcolumnswheretheuserdidntputanydata?

    Tags:mysql(PrevQ)(NextQ)

    User:roflwaffle

    Answer byquassnoi

    ByusingNULLyoucandistinguishbetweenputnodataandputemptydata.

    http://stackoverflow.com/q/1267999http://stackoverflow.com/u/49887http://stackoverflow.com/q/1268017http://stackoverflow.com/u/55159

  • Somemoredifferences:

    ALENGTHofNULLisNULL,aLENGTHofanemptystringis0.

    NULLsaresortedbeforetheemptystrings.

    COUNT(message)willcountemptystringsbutnotNULLs

    YoucansearchforanemptystringusingaboundvariablebutnotforaNULL.Thisquery:SELECT*FROMmytableWHEREmytext=?

    willnevermatchaNULLinmytext,whatevervalueyoupassfromtheclient.TomatchNULLs,youllhavetouseotherquery:SELECT*FROMmytableWHEREmytextISNULL

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQL:Countoccurrencesofdistinctvalues

    Tags:mysql(PrevQ)(NextQ)

    IamtryingtofindaMySQLquerythatwillfinddistinctvaluesinaparticularfield,countthenumberofoccurrencesofthatvalueandthenordertheresultsbythecount.

    exampledbidname-----------1Mark2Mike3Paul4Mike5Mike6John7Mark

    expectedresultnamecount----------Mike3Mark2Paul1John1

    Thanks

    Tags:mysql(PrevQ)(NextQ)

    User:jimmyj

    Answer byamberSELECTname,COUNT(*)ascountFROMtablenameGROUPBYnameORDERBYcountDESC;

    http://stackoverflow.com/q/1346345http://stackoverflow.com/u/2083http://stackoverflow.com/q/1346352http://stackoverflow.com/u/148870

  • Tags:mysql(PrevQ)(NextQ)

    Q:HowdoIchangethedatatypeforacolumninMySQL?

    Tags:mysql(PrevQ)(NextQ)

    Iwanttochangethedatatypeofmultiplecolumnsfromfloattoint.Whatisthesimplestwaytodothis?

    Thereisnodatatoworryabout,yet.

    Tags:mysql(PrevQ)(NextQ)

    User:eric-wilson

    Answer byyannick-motton

    http://dev.mysql.com/doc/refman/5.1/en/alter-table.htmlALTERTABLEtablenameMODIFYcolumnnameINTEGER;

    Thiswillchangethedatatypeofgivencolumn

    Dependingonhowmanycolumnsyouwishtomodifyitmightbebesttogenerateascript,orusesomekindofmysqlclientGUI

    Tags:mysql(PrevQ)(NextQ)

    Q:HowtogetIDofthelastupdatedrowinMySQL?

    Tags:mysql(PrevQ)(NextQ)

    HowdoIgettheIDofthelastupdatedrowinMySQLusingPHP?

    Tags:mysql(PrevQ)(NextQ)

    User:avinash

    Answer bypomyk

    Ivefoundananswertothisproblem:)SET@update_id:=0;UPDATEsome_tableSETcolumn_name='value',id=(SELECT@update_id:=id)WHEREsome_other_column='blah'LIMIT1;SELECT@update_id;

    EDITbyaefxx

    ThistechniquecanbefurtherexpandedtoretrievetheIDofeveryrowaffectedbyanupdatestatement:SET@uids:=null;UPDATEfootableSETfoo='bar'

    http://stackoverflow.com/q/1356866http://stackoverflow.com/u/82474http://stackoverflow.com/q/1356875http://stackoverflow.com/u/68822http://dev.mysql.com/doc/refman/5.1/en/alter-table.htmlhttp://stackoverflow.com/q/1388025http://stackoverflow.com/u/148478http://stackoverflow.com/q/1751282http://stackoverflow.com/u/169213

  • WHEREfooid>5AND(SELECT@uids:=CONCAT_WS(',',fooid,@uids));SELECT@uids;

    ThiswillreturnastringwithalltheIDsconcatenatedbyacolon.

    Tags:mysql(PrevQ)(NextQ)

    Q:Howtogetnext/previousrecordinMySQL?

    Tags:mysql(PrevQ)(NextQ)

    SayIhaverecordswithIDs3,4,7,9andIwanttobeabletogofromonetoanotherbynavitagionvianext/previouslinks.Theproblemis,thatIdontknowhowtofetchrecordwithnearesthigherID.

    SowhenIhaverecordwithID4,Ineedtobeabletofetchnextexistingrecord,whichwouldbe7.ThequerywouldprobablylooksomethinglikeSELECT*FROMfooWHEREid=4OFFSET1

    HowcanIfetchnext/previousrecordwithoutfetchingwholeresultsetandmanualyiterating?

    ImusingMySQL5.

    Tags:mysql(PrevQ)(NextQ)

    User:jakub-arnold

    Answer bylongneck

    next:select*fromfoowhereid=(selectmin(id)fromfoowhereid>4)

    previous:select*fromfoowhereid=(selectmax(id)fromfoowhereid4ORDERBYidLIMIT1;

    previousrecord:SELECT*FROMfooWHEREidmytagfieldissettoUNIQUEandIsimplywantthedatabasetoignoreanyduplicatetag.INSERTINTOtable_tags(tag)VALUES('tag_a'),('tab_b'),('tag_c')ONDUPLICATEKEYIGNORE'*theoffendingtagandcarryon*'

    oreventhiswouldbeacceptableINSERTINTOtable_tags(tag)VALUES('tag_a'),('tab_b'),('tag_c')ONDUPLICATEKEYUPDATE'*theoffendingtagandcarryon*'

    Tags:mysql(PrevQ)(NextQ)

    User:good-bye

    Answer bythummper

    WouldsuggestNOTusingINSERTIGNOREasitignoresALLerrors(ieitsasloppyglobalignore).Instead,sinceinyourexampletagistheuniquekey,use:INSERTINTOtable_tags(tag)VALUES('tag_a'),('tab_b'),('tag_c')ONDUPLICATEKEYUPDATEtag=tag;

    onduplicatekeyproduces:

    http://stackoverflow.com/u/263960http://stackoverflow.com/q/2215359http://stackoverflow.com/u/21441http://stackoverflow.com/q/2215360http://stackoverflow.com/u/45531http://www.php.net/manual/en/function.date.php#85692http://stackoverflow.com/q/2366813http://stackoverflow.com/u/195192http://stackoverflow.com/q/4920619http://stackoverflow.com/u/606330

  • QueryOK,0rowsaffected(0.07sec)

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQLqueryStringcontains

    Tags:mysql(PrevQ)(NextQ)

    IvebeentryingtofigureouthowIcanmakeaquerywithMySQLthatchecksifthevalue(string$haystack)inacertaincolumncontainscertaindata(string$needle),likethis:mysql_query("SELECT*FROM`table`WHERE`column`.contains('{$needle}')");

    InPHP,thefunctioniscalledsubstr($haystack,$needle),somaybe:WHEREsubstr(`column`,'{$needle}')=1

    Tags:mysql(PrevQ)(NextQ)

    User:arik

    Answer bywolph

    Quitesimpleactually:mysql_query("SELECT*FROM`table`WHERE`column`LIKE'%{$needle}%'");

    The%isawildcardforanycharacter.Donotethatthiscangetslowonverylargedatasetssoifyourdatabasegrowsyoullneedtousefulltextindices.

    Answer byomg-ponies

    Use:SELECT*FROM`table`WHEREINSTR(`column`,'{$needle}')>0

    Reference:

    INSTR

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQL:Howtocopyrows,butchangeafewfields?

    http://stackoverflow.com/q/2602252http://stackoverflow.com/u/299711http://stackoverflow.com/q/2602274http://stackoverflow.com/u/54017http://stackoverflow.com/q/2602280http://stackoverflow.com/u/135152http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_instrhttp://stackoverflow.com/q/2783150

  • Tags:mysql(PrevQ)(NextQ)

    IhavealargenumberofrowsthatIwouldliketocopy,butIneedtochangeonefield.

    IcanselecttherowsthatIwanttocopy:select*fromTablewhereEvent_ID="120"

    NowIwanttocopyallthoserowsandcreatenewrowswhilesettingtheEvent_IDto155.HowcanIaccomplishthis?

    Tags:mysql(PrevQ)(NextQ)

    User:andrew

    Answer bydcpINSERTINTOTable(Event_ID,col2...)SELECT"155",col2...FROMTableWHEREEvent_ID="120"

    Here,thecol2,representtheremainingcolumns(theonesotherthanEvent_ID)inyourtable.

    Answer byalex-christodoulou

    Thisisasolutionwhereyouhavemanyfieldsinyourtableanddontwanttogetafingercrampfromtypingallthefields,justtypetheonesneeded:)

    Howtocopysomerowsintothesametable,withsomefieldshavingdifferentvalues:

    1. Createatemporarytablewithalltherowsyouwanttocopy2. Updatealltherowsinthetemporarytablewiththevaluesyouwant3. Ifyouhaveanautoincrementfield,youshouldsetittoNULLinthetemporarytable4. Copyalltherowsofthetemporarytableintoyouroriginaltable5. Deletethetemporarytable

    Yourcode:CREATEtabletemporary_tableASSELECT*FROMoriginal_tableWHEREEvent_ID="155";

    UPDATEtemporary_tableSETEvent_ID="120";

    UPDATEtemporary_tableSETID=NULL

    INSERTINTOoriginal_tableSELECT*FROMtemporary_table;

    DROPTABLEtemporary_table

    Generalscenariocode:CREATEtabletemporary_tableASSELECT*FROMoriginal_tableWHERE;

    UPDATEtemporary_tableSET=,=,...;

    UPDATEtemporary_tableSET=NULL;

    http://stackoverflow.com/u/48523http://stackoverflow.com/q/2783162http://stackoverflow.com/u/109360http://stackoverflow.com/q/15344327http://stackoverflow.com/u/1611330

  • INSERTINTOoriginal_tableSELECT*FROMtemporary_table;

    DROPTABLEtemporary_table

    Simplified/condensedcode:CREATETEMPORARYTABLEtemporary_tableASSELECT*FROMoriginal_tableWHERE;

    UPDATEtemporary_tableSET=NULL,=,=,...;

    INSERTINTOoriginal_tableSELECT*FROMtemporary_table;

    AscreationofthetemporarytableusestheTEMPORARYkeyworditwillbedroppedautomaticallywhenthesessionfinishes(as@ar34zsuggested).

    Tags:mysql(PrevQ)(NextQ)

    Q:caseinsensitiveforsqlLIKEwildcardstatement

    Tags:mysql(PrevQ)(NextQ)

    Sorryifthisisarepeat.IlookedaroundsomeanddidntfindwhatIwasaftersoheregoes.SELECT*FROMtreesWHEREtrees.`title`LIKE'%elm%'

    Thisworksfine,butnotifthetreeisnamedElmorELMectHowdoImakeSQLcaseinsensitiveforthiswild-cardsearch?

    Again,apologiesifthisisrepeated.

    Oh,usingMySql5onapache.

    Tags:mysql(PrevQ)(NextQ)

    User:david-morrow

    Answer byquassnoiSELECT*FROMtreesWHEREtrees.`title`COLLATEUTF8_GENERAL_CILIKE'%elm%'

    Answer bycwallenpoole

    Ivealwayssolvedthisusinglower:SELECT*FROMtreesWHERELOWER(trees.title)LIKE'%elm%'

    Tags:mysql(PrevQ)(NextQ)

    Q:mysql_fetch_array()/mysql_fetch_assoc()/mysql_fetch_row()expectsparameter1toberesourceormysqli_result,booleangiven

    http://stackoverflow.com/q/2876789http://stackoverflow.com/u/279558http://stackoverflow.com/q/2876820http://stackoverflow.com/u/55159http://stackoverflow.com/q/2876802http://stackoverflow.com/u/57191http://stackoverflow.com/q/2973202

  • Tags:mysql(PrevQ)(NextQ)

    IamtryingtoselectdatafromaMySQLtable,butIgetoneofthefollowingerrormessages:

    mysql_fetch_array()expectsparameter1toberesource,booleangiven

    or

    mysqli_fetch_array()expectsparameter1tobemysqli_result,booleangiven

    Thisismycode:$username=$_POST['username'];$password=$_POST['password'];

    $result=mysql_query('SELECT*FROMUsersWHEREUserNameLIKE$username');

    while($row=mysql_fetch_array($result)){echo$row['FirstName'];}

    Thesameappliestocodelike$result=mysqli_query($mysqli,'SLECT');//mysqli_fetch_array()expectsparameter1tobemysqli_result,booleangivenwhile($row=mysqli_fetch_array($result)){...

    and$result=$mysqli->query($mysqli,'SELCT');//Calltoamemberfunctionfetch_assoc()onanon-objectwhile($row=$result->fetch_assoc($result)){...

    and$result=$pdo->query('SLECT',PDO::FETCH_ASSOC);//Invalidargumentsuppliedforforeach()foreach($resultas$row){...

    and$stmt=$mysqli->prepare('SLECT');//Calltoamemberfunctionbind_param()onanon-object$stmt->bind_param(...)

    and$stmt=$pdo->prepare('SLECT');//CalltoamemberfunctionbindParam()onanon-object$stmt->bindParam(...)

    Tags:mysql(PrevQ)(NextQ)

    User:iamjonesy

    Answer byscompt.com

    Aquerymayfailforvariousreasonsinwhichcaseboththemysql_*andthemysqliextensionwillreturnfalsefromtheirrespectivequeryfunctions/methods.Youneedto

    http://stackoverflow.com/u/299871http://stackoverflow.com/q/2973209http://stackoverflow.com/u/111777

  • testforthaterrorconditionandhandleitaccordingly.

    mysql_*extension :

    NOTEThemysql_functionsaredeprecatedandwillberemovedwiththeupcomingphpversion7.

    Check$resultbeforepassingittomysql_fetch_array.Youllfindthatitsfalsebecausethequeryfailed.Seethemysql_query documentationforpossiblereturnvaluesandsuggestionsforhowtodealwiththem.Skipcodeblock$username=mysql_real_escape_string($_POST['username']);$password=$_POST['password'];$result=mysql_query("SELECT*FROMUsersWHEREUserNameLIKE'$username'");

    if($result===FALSE){die(mysql_error());//TODO:bettererrorhandling}

    while($row=mysql_fetch_array($result)){echo$row['FirstName'];}

    mysqliextensionproceduralstyle:Skipcodeblock$username=mysqli_real_escape_string($mysqli,$_POST['username']);$result=mysqli_query($mysqli,"SELECT*FROMUsersWHEREUserNameLIKE'$username'");

    //mysqli_queryreturnsfalseifsomethingwentwrongwiththequeryif($result===FALSE){yourErrorHandler(mysqli_error($mysqli));}else{//asofphp5.4mysqli_resultimplementsTraversable,soyoucanuseitwithforeachforeach($resultas$row){...

    oo-style:Skipcodeblock$username=$mysqli->escape_string($_POST['username']);$result=$mysqli->query("SELECT*FROMUsersWHEREUserNameLIKE'$username'");

    if($result===FALSE){yourErrorHandler($mysqli->error);//or$mysqli->error_list}else{//asofphp5.4mysqli_resultimplementsTraversable,soyoucanuseitwithforeachforeach($resultas$row){...

    usingapreparedstatement:Skipcodeblock$stmt=$mysqli->prepare('SELECT*FROMUsersWHEREUserNameLIKE?');if(!$stmt){yourErrorHandler($mysqli->error);//or$mysqli->error_list}elseif(!$stmt->bind_param('s',$_POST['username'])){yourErrorHandler($stmt->error);//or$stmt->error_list}elseif(!$stmt->execute()){yourErrorHandler($stmt->error);//or$stmt->error_list

    http://docs.php.net/book.mysqlhttp://php.net/manual/en/function.mysql-query.phphttp://docs.php.net/book.mysqli

  • }else{$result=$stmt->get_result();//asofphp5.4mysqli_resultimplementsTraversable,soyoucanuseitwithforeachforeach($resultas$row){...

    Theseexamplesonlyillustratewhatshouldbedone(errorhandling),nothowtodoit.Productioncodeshouldntuseordie whenoutputtingHTML,elseitwill(attheveryleast)generateinvalidHTML.Also,databaseerrormessagesshouldntbedisplayedtonon-adminusers,asitdisclosestoomuchinformation .

    Answer byjohn-conde

    Thiserrormessageisdisplayedwhenyouhaveanerrorinyourquerywhichcausedittofail.Itwillmanifestitselfwhenusing:

    mysql_fetch_array/mysqli_fetch_array()mysql_fetch_assoc()/mysqli_fetch_assoc()mysql_num_rows()/mysqli_num_rows()

    Note:Thiserrordoesnotappearifnorowsareaffectedbyyourquery.Onlyaquerywithaninvalidsyntaxwillgeneratethiserror.

    TroubleshootingSteps

    Makesureyouhaveyourdevelopmentserverconfiguredtodisplayallerrors.Youcandothisbyplacingthisatthetopofyourfilesorinyourconfigfile:error_reporting(-1); .Ifyouhaveanysyntaxerrorsthiswillpointthemouttoyou.

    Usemysql_error() .mysql_error()willreportanyerrorsMySQLencounteredwhileperformingyourquery.

    Sampleusage:mysql_connect($host,$username,$password)ordie("cannotconnect");mysql_select_db($db_name)ordie("cannotselectDB");

    $sql="SELECT*FROMtable_name";$result=mysql_query($sql);

    if(false===$result){echomysql_error();}

    RunyourqueryfromtheMySQLcommandlineoratoollikephpMyAdmin .Ifyouhaveasyntaxerrorinyourquerythiswilltellyouwhatitis.

    Makesureyourquotesarecorrect.Amissingquotearoundthequeryoravaluecancauseaquerytofail.

    Makesureyouareescapingyourvalues.Quotesinyourquerycancauseaquerytofail(andalsoleaveyouopentoSQLinjections).Usemysql_real_escape_string() toescapeyourinput.

    Makesureyouarenotmixingmysqli_*andmysql_*functions.Theyarenotthe

    http://www.phpfreaks.com/blog/or-die-must-diehttp://msdn.microsoft.com/en-us/library/ms995351.aspx#securityerrormessages_topic2http://stackoverflow.com/q/11674313http://stackoverflow.com/u/250259http://php.net/manual/en/function.error-reporting.phphttp://us3.php.net/manual/en/function.mysql-error.phphttp://www.phpmyadmin.net/home_page/index.phphttp://php.net/manual/en/function.mysql-real-escape-string.php

  • samethingandcannotbeusedtogether.(Ifyouregoingtochooseoneortheotherstickwithmysqli_*.Seebelowforwhy.)

    Othertips

    mysql_*functionsshouldnotbeusedfornewcode.Theyarenolongermaintainedandthecommunityhasbegunthedeprecationprocess .Insteadyoushouldlearnaboutpreparedstatements anduseeitherPDO orMySQLi .Ifyoucantdecide,thisarticle willhelptochoose.Ifyoucaretolearn,hereisgoodPDOtutorial .

    Answer bynik

    Erroroccurredherewasduetotheuseofsinglequotes(').Youcanputyourquerylikethis:mysql_query("SELECT*FROMUsersWHEREUserNameLIKE'".mysql_real_escape_string($username)."'");

    Itsusingmysql_real_escape_stringforpreventionofSQLinjection.ThoughweshoulduseMySQLiorPDO_MYSQLextensionforupgradedversionofPHP(PHP5.5.0andlater),butforolderversionsmysql_real_escape_stringwilldothetrick.

    Tags:mysql(PrevQ)(NextQ)

    Q:HowtoexportamysqldatabaseusingCommandPrompt?

    Tags:mysql(PrevQ)(NextQ)

    IhaveadatabasethatisquitelargesoIwanttoexportitusingCommandPromptbutIdontknowhowto.

    IamusingWAMP.

    Tags:mysql(PrevQ)(NextQ)

    User:starx

    Answer bystarx

    Firstcheckifyourcommandlinerecognizesmysqlcommand.Ifnotgotocommand&typein:setpath=c:\wamp\bin\mysql\mysql5.1.36\bin

    Thenusethiscommandtoexportyourdatabase:mysqldump-uYourUser-pYourDatabaseName>wantedsqlfile.sql

    Youwillthenbepromptedforthedatabasepassword.

    Thisexportsthedatabasetothepathyouarecurrentlyin,whileexecutingthiscommand

    Note:Herearesomedetailedinstructions regardingbothimportandexport

    http://news.php.net/php.internals/53799http://en.wikipedia.org/wiki/Prepared_statementhttp://us2.php.net/pdohttp://php.net/mysqlihttp://php.net/manual/en/mysqlinfo.api.choosing.phphttp://wiki.hashphp.org/PDO_Tutorial_for_MySQL_Developershttp://stackoverflow.com/q/2973247http://stackoverflow.com/u/290583http://stackoverflow.com/q/3031412http://stackoverflow.com/u/295264http://stackoverflow.com/q/3031414http://stackoverflow.com/u/295264http://www.thegeekstuff.com/2008/09/backup-and-restore-mysql-database-using-mysqldump/#more-184

  • Answer bysrinivasan.s

    Simplyusethefollowingcommand,

    ForExport:mysqldump-u[user]-p[db_name]|gzip>[filename_to_compress.sql.gz]

    ForImport:gunzipcreatetablenumbers(adecimal(10,2),bfloat);mysql>insertintonumbersvalues(100,100);mysql>select@a:=(a/3),@b:=(b/3),@a*3,@b*3fromnumbers\G***************************1.row***************************@a:=(a/3):33.333333333@b:=(b/3):33.333333333333@a+@a+@a:99.999999999000000000000000000000@b+@b+@b:100

    Thedecimaldidexactlywhatssupposedtodoonthiscases,ittruncatedtherest,thuslosingthe1/3part.

    Soforsumsthedecimalisbetter,butfordivisionsthefloatisbetter,uptosomepoint,ofcourse.Imean,usingDECIMALwillnotgiveyouafailproofarithmeticinanymeans.

    Hopethishelps.

    Answer bymichael-petrotta

    Afloatinmostenvironmentsisabinaryfloating-pointtype.Itcanaccuratelystorebase-2values(toacertainpoint),butcannotaccuratelystoremanybase-10(decimal)values.Floatsaremostappropriateforscientificcalculations.Theyrenotappropriateformostbusiness-orientedmath,andinappropriateuseoffloatswillbiteyou.Manydecimalvaluescantbeexactlyrepresentedinbase-2.0.1cant,forinstance,andsoyouseestrangeresultslike1.0-0.1=0.8999999.

    Decimalsstorebase-10numbers.Decimalisangoodtypeformostbusinessmath(butanybuilt-inmoneytypeismoreappropriateforfinancialcalculations),wheretherangeofvaluesexceedsthatprovidedbyintegertypes,andfractionalvaluesareneeded.Decimals,asthenameimplies,aredesignedforbase-10numbers-theycanaccuratelystoredecimalvalues(again,toacertainpoint).

    http://stackoverflow.com/q/5150274http://stackoverflow.com/u/278470http://stackoverflow.com/q/5150314http://stackoverflow.com/u/518445http://lists.mysql.com/mysql/201710http://stackoverflow.com/q/5150345http://stackoverflow.com/u/23897

  • Tags:mysql(PrevQ)(NextQ)

    Q:MySQLInsertintomultipletables?(Databasenormalization?)

    Tags:mysql(PrevQ)(NextQ)

    Itriedsearchingawaytoinsertinformationinmultipletablesinthesamequery,butfoundoutitsimpossible?SoIwanttoinsertitbysimplyusingmutliplequeriesi.e;INSERTINTOusers(username,password)VALUES('test','test')INSERTINTOprofiles(userid,bio,homepage)VALUES('[idoftheuserhere?]','Helloworld!','http://www.stackoverflow.com')

    ButhowcanIgivetheauto-incrementidfromtheusertothemanualuseridfortheprofiletable?

    Tags:mysql(PrevQ)(NextQ)

    User:jay-wit

    Answer bykonerak

    No,youcantinsertintomultipletablesinoneMySQLcommand.Youcanhoweverusetransactions.BEGIN;INSERTINTOusers(username,password)VALUES('test','test');INSERTINTOprofiles(userid,bio,homepage)VALUES(LAST_INSERT_ID(),'Helloworld!','http://www.stackoverflow.com');COMMIT;

    HavealookatLAST_INSERT_ID() toreuseautoincrementvalues.

    Edit:yousaidAfterallthistimetryingtofigureitout,itstilldoesntwork.CantIsimplyputthejustgeneratedIDina$varandputthat$varinalltheMySQLcommands?

    Letmeelaborate:thereare3possiblewayshere:

    1. Isthecodeyouseeabove.ThisdoesitallinMySQL,andtheLAST_INSERT_ID()inthesecondstatementwillautomaticallybethevalueoftheautoincrement-columnthatwasinsertedinthefirststatement.

    Unfortunately,whenthesecondstatementitselfinsertsrowsinatablewithanauto-incrementcolumn,theLAST_INSERT_ID()willbeupdatedtothatoftable2,andnottable1.Ifyoustillneedthatoftable1afterwards,wewillhavetostoreitinavariable.Thisleadsustoways2and3:

    2. WillstocktheLAST_INSERT_ID()inaMySQLvariable:INSERTSELECTLAST_INSERT_ID()INTO@mysql_variable_here;INSERTINTOtable2(@mysql_variable_here,...);INSERTINTOtable3(@mysql_variable_here,...);

    3. WillstocktheLAST_INSERT_ID()inaphpvariable(oranylanguagethatcanconnecttoadatabase,ofyourchoice):

    http://stackoverflow.com/q/5178697http://stackoverflow.com/u/630020http://stackoverflow.com/q/5178713http://stackoverflow.com/u/327563http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html

  • INSERTUseyourlanguagetoretrievetheLAST_INSERT_ID(),eitherbyexecutingthatliteralstatementinMySQL,orusingforexamplephpsmysql_insert_id()whichdoesthatforyouINSERT[useyourphpvariablehere]

    WARNING

    Whateverwayofsolvingthisyouchoose,youmustdecidewhatshouldhappenshouldtheexecutionbeinterruptedbetweenqueries(forexample,yourdatabase-servercrashes).Ifyoucanlivewithsomehavefinished,othersnot,dontreadon.

    Ifhoweveryoudecideeitherallqueriesfinish,ornonefinish-Idonotwantrowsinsometablesbutnomatchingrowsinothers,Ialwayswantmydatabasetablestobeconsistent,youneedtowrapallstatementsinatransaction.ThatswhyIusedtheBEGINandCOMMIThere.

    Commentagainifyouneedmoreinfo:)

    Tags:mysql(PrevQ)(NextQ)

    Q:CantconnecttolocalMySQLserverthroughsocket/var/mysql/mysql.sock(38)

    Tags:mysql(PrevQ)(NextQ)

    Iamhavingabigproblemtryingtoconnecttomysql.WhenIrun:/usr/local/mysql/bin/mysqlstart

    Ihavethefollowingerror:Can'tconnecttolocalMySQLserverthroughsocket'/var/mysql/mysql.sock'(38)

    Idohavemysql.sockunderthe/var/mysqldirectory.

    In/etc/my.cnfIhave:[client]port=3306socket=/var/mysql/mysql.sock

    [mysqld]port=3306socket=/var/mysql/mysql.sockkey_buffer_size=16Mmax_allowed_packet=8M

    andin/etc/php.iniIhave:;DefaultsocketnameforlocalMySQLconnects.Ifempty,usesthebuilt-in;MySQLdefaults.mysql.default_socket=/var/mysql/mysql.sock

    Ihaverestartedapacheusingsudo/opt/local/apache2/bin/apachectlrestart

    http://stackoverflow.com/q/5376427

  • ButIstillhavetheerror.

    Otherwise,IdontknowifthatsrelevantbutwhenIdomysql_config--socketsIget--socket[/tmp/mysql.sock]

    Tags:mysql(PrevQ)(NextQ)

    User:lambivist

    Answer bymarimaf

    Ifyourfilemy.cnf(usuallyinthe/etc/mysql/folder)iscorrectlyconfiguredwithsocket=/var/lib/mysql/mysql.sock

    youcancheckifmysqlisrunningwiththefollowingcommand:mysqladmin-uroot-pstatus

    trychangingyourpermissiontomysqlfolder.Ifyouareworkinglocally,youcantry:sudochmod-R755/var/lib/mysql/

    thatsolveditforme

    Answer bywaqas

    areyousureyouinstalledmysqlaswellasmysqlserver..

    ForexampletoinstallmySqlserverIlluseyumorapttoinstallbothmysqlcommandlinetoolandtheserver:yum-yinstallmysqlmysql-server(orapt-getinstallmysqlmysql-server)

    EnabletheMySQLservice:/sbin/chkconfigmysqldon

    StarttheMySQLserver:/sbin/servicemysqldstart

    afterwardssettheMySQLrootpassword:mysqladmin-urootpassword'new-password'(withthequotes)

    Ihopeithelps.

    Answer bymaurizio

    Aquickworkaroundthatworkedforme:tryusingthelocalipaddress(127.0.0.1)insteadoflocalhostinmysql_connect().ThisforcesphptoconnectthroughTCP/IPinsteadofaunixsocket.

    Tags:mysql(PrevQ)(NextQ)

    http://stackoverflow.com/u/615503http://stackoverflow.com/q/8084959http://stackoverflow.com/u/592795http://stackoverflow.com/q/11178032http://stackoverflow.com/u/819344http://stackoverflow.com/q/8339695http://stackoverflow.com/u/422803

  • Q:MySQLOPTIMIZEalltables?

    Tags:mysql(PrevQ)(NextQ)

    MySQLhasanOPTIMIZETABLE commandwhichcanbeusedtoreclaimunusedspaceinaMySQLinstall.Isthereaway(built-incommandorcommonstoredprocedure)torunthisoptimizationforeverytableinthedatabaseand/orserverinstall,oristhissomethingyoudhavetoscriptupyourself?

    Tags:mysql(PrevQ)(NextQ)

    User:alan-storm

    Answer byike-walker

    Youcanusemysqlcheck todothisatthecommandline.

    Onedatabase:mysqlcheck-o

    Alldatabases:mysqlcheck-o--all-databases

    Tags:mysql(PrevQ)(NextQ)

    Q:GetallcolumnsfromallMySQLtables

    Tags:mysql(PrevQ)(NextQ)

    IsthereafastwayofgettingallcolumnnamesfromalltablesinMySQL,withouthavingtolistallthetables?

    Tags:mysql(PrevQ)(NextQ)

    User:dieter

    Answer bynick-rulezselect*frominformation_schema.columnswheretable_schema='your_db'orderbytable_name,ordinal_position

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQLstringreplace

    Tags:mysql(PrevQ)(NextQ)

    Ihaveacolumncontainingurls(id,url):

    http://stackoverflow.com/q/5474662http://dev.mysql.com/doc/refman/5.1/en/optimize-table.htmlhttp://stackoverflow.com/u/4668http://stackoverflow.com/q/5475582http://stackoverflow.com/u/233196http://dev.mysql.com/doc/refman/5.0/en/mysqlcheck.htmlhttp://stackoverflow.com/q/5648420http://stackoverflow.com/u/704164http://stackoverflow.com/q/5648713http://stackoverflow.com/u/344491http://stackoverflow.com/q/5956993

  • http://www.example.com/articles/updates/43http://www.example.com/articles/updates/866http://www.example.com/articles/updates/323http://www.example.com/articles/updates/seo-urlhttp://www.example.com/articles/updates/4?something=test

    Idliketochangethewordupdatestonews.Isitpossibletodothiswithascript?

    Tags:mysql(PrevQ)(NextQ)

    User:n00b

    Answer bygiraldiUPDATEyour_tableSETyour_field=REPLACE(your_field,'articles/updates/','articles/news/')WHEREyour_fieldLIKE'%articles/updates/%'

    http://to.ly/iLjP

    Answer byonteria_

    Yes,MySQLhasaREPLACE()function:mysql>SELECTREPLACE('www.mysql.com','w','Ww');->'WwWwWw.mysql.com'

    http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replace

    NotethatitseasierifyoumakethatanaliaswhenusingSELECTSELECTREPLACE(string_column,'search','replace')asurl.

    Tags:mysql(PrevQ)(NextQ)

    Q:mySQLselectonecolumnDISTINCT,withcorrespondingothercolumns

    Tags:mysql(PrevQ)(NextQ)IDFirstNameLastName1JohnDoe2BugsBunny3JohnJohnson

    IwanttoselectDISTINCTresultsfromtheFirstNamecolumn,butIneedthecorrespondingIDandLastName.

    TheresultsetneedstoshowonlyoneJohn,butwithanIDof1andaLastNameofDoe.

    Tags:mysql(PrevQ)(NextQ)

    User:m-r

    Answer bydiecho

    trythisquerySELECTID,FirstName,LastNameFROMtableGROUPBY(FirstName)

    http://stackoverflow.com/u/276315http://stackoverflow.com/q/14586441http://stackoverflow.com/u/851045http://to.ly/iLjPhttp://stackoverflow.com/q/5957021http://stackoverflow.com/u/742496http://dev.mysql.com/doc/refman/5.0/en/string-functions.html#function_replacehttp://stackoverflow.com/q/5967130http://stackoverflow.com/u/638531http://stackoverflow.com/q/5967209http://stackoverflow.com/u/155861

  • Tags:mysql(PrevQ)(NextQ)

    Q:MySqlexportschemawithoutdata

    Tags:mysql(PrevQ)(NextQ)

    ImusingaMySqldatabasewithaJavaprogram,nowIwanttogivetheprogramtosomebodyelse.

    HowtoexporttheMySqldatabasestructurewithoutthedatainit,justthestructure?

    Tags:mysql(PrevQ)(NextQ)

    User:darth-blue-ray

    Answer bydaric

    Youcandowiththeno-dataoptionwithmysqldumpcommandmysqldump-uroot-p--no-datadbname>schema.sql

    Answer byonteria_

    Yes,youcanusemysqldumpwiththe--no-dataoption:mysqldump-uuser-hlocalhost--no-data-pdatabase>database.sql

    Tags:mysql(PrevQ)(NextQ)

    Q:HowcanyoudeterminehowmuchdiskspaceaparticularMySQLtableistakingup?

    Tags:mysql(PrevQ)(NextQ)

    IsthereaquickwaytodeterminehowmuchdiskspaceaparticularMySQLtableistakingup?ThetablemaybeMyISAMorInnodb.

    Tags:mysql(PrevQ)(NextQ)

    User:dan

    Answer byrolandomysqldba

    Foratablemydb.mytablerunthisfor:

    BYTES

    SELECT(data_length+index_length)tablesizeFROMinformation_schema.tablesWHEREtable_schema='mydb'andtable_name='mytable';

    http://stackoverflow.com/q/6175473http://stackoverflow.com/u/753983http://stackoverflow.com/q/6175506http://stackoverflow.com/u/611232http://stackoverflow.com/q/6175500http://stackoverflow.com/u/742496http://stackoverflow.com/q/6474591http://stackoverflow.com/u/232417http://stackoverflow.com/q/6474642http://stackoverflow.com/u/491757

  • KILOBYTES

    SELECT(data_length+index_length)/power(1024,1)tablesize_kbFROMinformation_schema.tablesWHEREtable_schema='mydb'andtable_name='mytable';

    MEGABYTES

    SELECT(data_length+index_length)/power(1024,2)tablesize_mbFROMinformation_schema.tablesWHEREtable_schema='mydb'andtable_name='mytable';

    GIGABYTES

    SELECT(data_length+index_length)/power(1024,3)tablesize_gbFROMinformation_schema.tablesWHEREtable_schema='mydb'andtable_name='mytable';

    GENERIC

    HereisagenericquerywherethemaximumunitdisplayisTB(TeraBytes)SkipcodeblockSELECTCONCAT(FORMAT(DAT/POWER(1024,pw1),2),'',SUBSTR(units,pw1*2+1,2))DATSIZE,CONCAT(FORMAT(NDX/POWER(1024,pw2),2),'',SUBSTR(units,pw2*2+1,2))NDXSIZE,CONCAT(FORMAT(TBL/POWER(1024,pw3),2),'',SUBSTR(units,pw3*2+1,2))TBLSIZEFROM(SELECTDAT,NDX,TBL,IF(px>4,4,px)pw1,IF(py>4,4,py)pw2,IF(pz>4,4,pz)pw3FROM(SELECTdata_lengthDAT,index_lengthNDX,data_length+index_lengthTBL,FLOOR(LOG(IF(data_length=0,1,data_length))/LOG(1024))px,FLOOR(LOG(IF(index_length=0,1,index_length))/LOG(1024))py,FLOOR(LOG(IF(data_length+index_length=0,1,data_length+index_length))/LOG(1024))pzFROMinformation_schema.tablesWHEREtable_schema='mydb'ANDtable_name='mytable')AA)A,(SELECT'BKBMBGBTB'units)B;

    GiveitaTry!!!

    Tags:mysql(PrevQ)(NextQ)

    Q:MYSQLUpdateStatementInnerJoinTables

    Tags:mysql(PrevQ)(NextQ)

    Ihavenoideawhattheproblemis.UsingMySQL5.0igetacompileerrorwhenattemptingtorunthefollowingMYSQLupdatestatementUPDATEbSETb.mapx=g.latitude,b.mapy=g.longitudeFROMbusinessASbINNERJOINbusiness_geocodegONb.business_id=g.business_idWHERE(b.mapx=''orb.mapx=0)and

    http://stackoverflow.com/q/8057565

  • g.latitude>0

    allthefieldnamesarecorrect.Anythoughts?

    Tags:mysql(PrevQ)(NextQ)

    User:vibration-of-life

    Answer byasaph

    Trythis:UPDATEbusinessASbINNERJOINbusiness_geocodeASgONb.business_id=g.business_idSETb.mapx=g.latitude,b.mapy=g.longitudeWHERE(b.mapx=''orb.mapx=0)andg.latitude>0

    Update:

    Sinceyousaidthequeryyieldedasyntaxerror,IcreatedsometablesthatIcouldtestitagainstandconfirmedthatthereisnosyntaxerrorinmyquery:Skipcodeblockmysql>createtablebusiness(business_idintunsignedprimarykeyauto_increment,mapxvarchar(255),mapyvarchar(255))engine=innodb;QueryOK,0rowsaffected(0.01sec)

    mysql>createtablebusiness_geocode(business_geocode_idintunsignedprimarykeyauto_increment,business_idintunsignednotnull,latitudevarchar(255)notnull,longitudevarchar(255)notnull,foreignkey(business_id)referencesbusiness(business_id))engine=innodb;QueryOK,0rowsaffected(0.01sec)

    mysql>UPDATEbusinessASb->INNERJOINbusiness_geocodeASgONb.business_id=g.business_id->SETb.mapx=g.latitude,->b.mapy=g.longitude->WHERE(b.mapx=''orb.mapx=0)and->g.latitude>0;QueryOK,0rowsaffected(0.00sec)Rowsmatched:0Changed:0Warnings:0

    See?Nosyntaxerror.ItestedagainstMySQL5.5.8.

    Tags:mysql(PrevQ)(NextQ)

    Q:Howtochangemax_allowed_packetsize

    Tags:mysql(PrevQ)(NextQ)

    IamhavingaproblemwithBLOBfieldsinmyMySQLdatabase-whenuploadingfileslargerthanapprox1MBIgetanerrorPacketslargerthanmax_allowed_packetarenotallowed.

    Hereiswhativetried:

    InMySQLQueryBrowserIranashowvariableslike'max_allowed_packet'whichgaveme1048576.

    ThenIexecutethequerysetglobalmax_allowed_packet=33554432followedbyshowvariableslike'max_allowed_packet'-itgivesme33554432asexpected.

    http://stackoverflow.com/u/719316http://stackoverflow.com/q/8057585http://stackoverflow.com/u/166339http://stackoverflow.com/q/8062496

  • ButwhenIrestarttheMySQLserveritmagicallygoesbackto1048576.WhatamIdoingwronghere?

    Bonusquestion,isitpossibletocompressaBLOBfield?

    Tags:mysql(PrevQ)(NextQ)

    User:muleskinner

    Answer bymanuel

    Changeinthemy.inior~/.my.cnffilebyincludingthesinglelineunder[mysqld]sectioninyourfile:max_allowed_packet=500M

    thenrestarttheMySQLserviceandyouaredone.

    Seethedocumentation forfurtherinformation.

    Answer bytehshrike

    Themax_allowed_packet variablecanbesetgloballybyrunningaquery.

    However,ifyoudonotchangeitinthemy.inifile(asdragon112suggested),thevaluewillresetwhentheserverrestarts,evenifyousetitglobally.

    Tochangethesettingforeveryoneuntiltheserverrestarts:SETGLOBALmax_allowed_packet=1073741824;

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQL:determinewhichdatabaseisselected?

    Tags:mysql(PrevQ)(NextQ)

    Aftercallingmysql_select_dbtograbadatabase,isthereanywaytolateroutputthenameofthedatabasethatiscurrentlyselected?ThisseemsverybasicbutIcouldntfindanythingonphp.netorstackoverflow(allresultsarefornodatabaseselected).

    Tags:mysql(PrevQ)(NextQ)

    User:andrewtweber

    Answer bycwallenpoole

    Justusemysql_query(ormysqli_query,evenbetter,orusePDO,bestofall)with:SELECTDATABASE()FROMDUAL;

    Addendum:

    http://stackoverflow.com/u/246277http://stackoverflow.com/q/8062538http://stackoverflow.com/u/703595https://dev.mysql.com/doc/refman/5.5/en/packet-too-large.htmlhttp://stackoverflow.com/q/8062996http://stackoverflow.com/u/201789http://dev.mysql.com/doc/refman/5.5/en/server-system-variables.html#sysvar_max_allowed_packethttp://stackoverflow.com/q/8096550http://stackoverflow.com/u/704803http://stackoverflow.com/q/8096574http://stackoverflow.com/u/57191

  • ThereismuchdiscussionoverwhetherornotFROMDUALshouldbeincludedinthisornot.Onatechnicallevel,itisaholdoverfromOracleandcansafelyberemoved.Ifyouareinclined,youcanusethefollowinginstead:SELECTDATABASE();

    Thatsaid,itisperhapsimportanttonote,thatwhileFROMDUALdoesnotactuallydoanything,itisvalidMySQLsyntax.Fromastrictperspective,includingbracesinasinglelineconditionalinJavaScriptalsodoesnotdoanything,butitisstillavalidpractice.

    Tags:mysql(PrevQ)(NextQ)

    Q:EnableremoteMySQLconnection:ERROR1045(28000):Accessdeniedforuser

    Tags:mysql(PrevQ)(NextQ)

    MySQL5.1.31runningonWindowsXP.

    FromthelocalMySQLserver(192.168.233.142)Icanconnectasrootasfollows:>mysql--host=192.168.233.142--user=root--password=redacted

    Fromaremotemachine(192.168.233.163),Icanseethatthemysqlportisopen:#telnet192.168.233.1423306Trying192.168.233.142Connectedto192.168.233.142(192.168.233.142).

    Butwhentryingtoconnecttomysqlfromtheremotemachine,Ireceive:#mysql--host=192.168.233.142--user=root--password=redactedERROR1045(28000):Accessdeniedforuser'root'@'192.168.233.163'(usingpassword:YES)

    Ihaveonly2entriesinmysql.user:HostUserPassword--------------------------------------localhostroot*blahblahblah%root[sameasabove]

    WhatmoredoIneedtodotoenableremoteaccess?

    EDIT

    AssuggestedbyPaulobelow,Itriedreplacingthemysql.userentryfor%withanIPspecificentry,somyusertablenowlookslikethis:HostUserPassword------------------------------------------localhostroot*blahblahblah192.168.233.163root[sameasabove]

    Ithenrestartedthemachine,buttheproblempersists.

    Tags:mysql(PrevQ)(NextQ)

    User:mike-chamberlain

    http://stackoverflow.com/q/8380797http://stackoverflow.com/u/289319

  • Answer byoctavio

    Youhavetoputthisasroot:GRANTALLPRIVILEGESON*.*TO'USERNAME'@'IP'IDENTIFIEDBY'PASSWORD'withgrantoption;

    ;

    whereIPistheIPyouwanttoallowaccessandUSERNAMEistheuseryouusetoconnect

    IfyouwanttoallowaccessfromanyIPjustput%insteadofyourIP

    andthenyouonlyhavetoputFLUSHPRIVILEGES;

    Orrestartmysqlserverandthatsit.

    Answer bydrumchaps

    IwasgettingthesameerroraftergrantingremoteaccessuntilImadethis:

    From/etc/mysql/my.cnf#Insteadofskip-networkingthedefaultisnowtolistenonlyon#localhostwhichismorecompatibleandisnotlesssecure.#bind-address=127.0.0.1

    (commentthisline:bind-address=127.0.0.1)

    Thenrunservicemysqlrestart.

    Answer byravi-kant

    BydefaultinMySQLserverremoteaccessisdisabled.Theprocesstoprovidearemoteaccesstouseris.

    1. GotomysqlbinfolderoraddittoPATH2. Logintorootbymysql-uroot-proot(orwhatevertherootpasswordis.)3. Onsuccessyouwillgetmysql>4. Providegrantaccessallforthatuser.

    GRANTALLPRIVILEGESON*.*TO'username'@'IP'IDENTIFIEDBY'password';

    HereIPisIPaddressforwhichyouwanttoallowremoteaccess,ifweput%anyIPaddresscanaccessremotely.

    Example:C:\Users\UserName>cdC:\ProgramFiles(x86)\MySQL\MySQLServer5.0\bin

    C:\ProgramFiles(x86)\MySQL\MySQLServer5.0\bin>mysql-uroot-proot

    mysql>GRANTALLPRIVILEGESON*.*TO'root'@'%'IDENTIFIEDBY'root';QueryOK,0rowsaffected(0.27sec)

    mysql>FLUSHPRIVILEGES;QueryOK,0rowsaffected(0.25sec)

    http://stackoverflow.com/q/12844804http://stackoverflow.com/u/1738901http://stackoverflow.com/q/21151255http://stackoverflow.com/u/3200527http://stackoverflow.com/q/19359062http://stackoverflow.com/u/2151298

  • Thisforaotheruser.mysql>GRANTALLPRIVILEGESON*.*TO'testUser'@'%'IDENTIFIEDBY'testUser';QueryOK,0rowsaffected(0.00sec)

    mysql>FLUSHPRIVILEGES;QueryOK,0rowsaffected(0.00sec)

    Hopethiswillhelp

    Tags:mysql(PrevQ)(NextQ)

    Q:HowdoIcheckifacolumnisemptyornullinmysql

    Tags:mysql(PrevQ)(NextQ)

    Ihaveacolumninatablewhichmightcontainnulloremptyvalues.HowdoIcheckifacolumnisemptyornullintherowspresentinatable.(e.g.nullor''or''or''and)

    Tags:mysql(PrevQ)(NextQ)

    User:priya

    Answer bymaek

    Thiswillselectallrowswheresome_colisNULLor''(emptystring)SELECT*FROMtableWHEREsome_colISNULLORsome_col='';

    Answer byonedaywhen

    AsdefinedbytheSQL-92Standard,whencomparingtwostringsofdifferingwidths,thenarrowervalueisright-paddedwithspacestomakeitissamewidthasthewidervalue.Therefore,allvaluesthatconsistexclusivelyinvolvingzeroormorespaceswillbedeemedtobeequale.g.''=''ISTRUE''=''ISTRUE''=''ISTRUE''=''ISTRUEetc

    Therefore,thisshouldworkregardlessofhowmanyspacesmakeupthesome_colvalue:SELECT*FROMTWHEREsome_colISNULLORsome_col='';

    ormoresuccinctly:SELECT*FROMTWHERENULLIF(some_col,'')ISNULL;

    Tags:mysql(PrevQ)(NextQ)

    http://stackoverflow.com/q/8470813http://stackoverflow.com/u/1004443http://stackoverflow.com/q/8470865http://stackoverflow.com/u/184600http://stackoverflow.com/q/8474327http://stackoverflow.com/u/15354

  • Q:DoesMySQLforeign_key_checksaffecttheentiredatabase?

    Tags:mysql(PrevQ)(NextQ)

    WhenIexecutethiscommandinmysql:SETFOREIGN_KEY_CHECKS=0;

    Doesitaffectthewholeengineoritisonlymycurrenttransaction?

    Tags:mysql(PrevQ)(NextQ)

    User:sean-nguyen

    Answer byalmo

    Itissession-based.Doatesttobesure,butthatsmyunderstandingofit.

    Answer byron-inbar

    Actually,therearetwoforeign_key_checksvariables:aglobalvariableandalocal(persession)variable.Uponconnection,thesessionvariableisinitializedtothevalueoftheglobalvariable.ThecommandSETforeign_key_checksmodifiesthesessionvariable.Tomodifytheglobalvariable,useSETGLOBALforeign_key_checksorSET@@global.foreign_key_checks.

    Consultthefollowingmanualsections:http://dev.mysql.com/doc/refman/5.7/en/using-system-variables.htmlhttp://dev.mysql.com/doc/refman/5.7/en/server-system-variables.html

    Tags:mysql(PrevQ)(NextQ)

    Q:MySQL:Selectonlyuniquevaluesfromacolumn

    Tags:mysql(PrevQ)(NextQ)

    IhaveaMySQLtablewhichcontainsthefollowingtypeofinformation:Dateproduct2011-12-12azd2011-12-12yxm2011-12-10sdx2011-12-10ssdd

    HereisanexampleofascriptIusetogetdatafromthistable:Skipcodeblock

  • $sql=mysql_query("SELECT*FROMbuyORDERBYDate");while($row=mysql_fetch_array($sql)){

    echo"buy".date("j,MY",strtotime($row["Date"]))."";

    }mysql_close($con);?>

    Thisscriptdisplayseverydatefromthetable,e.g.12.dec201112.dec.201110.dec.201110.dec.2011

    Iwouldliketoonlydisplayuniquedates,e.g.12.dec.201110.dec.2011

    Tags:mysql(PrevQ)(NextQ)

    User:meandme

    Answer bylon-rodenburg

    UsetheDISTINCT operatorinMySQL:SELECTDISTINCT(Date)ASDateFROMbuyORDERBYDateDESC;

    Tags:mysql(PrevQ)(NextQ)

    Q:ERROR1044(42000):Accessdeniedforuser@localhosttodatabasedb

    Tags:mysql(PrevQ)(NextQ)

    IwanttobeginwritingqueriesinMySQL.

    showgrantsshows:+--------------------------------------+|Grantsfor@localhost|+--------------------------------------+|GRANTUSAGEON*.*TO''@'localhost'|+--------------------------------------+

    Idonothaveanyuser-idbutwhenIwanttomakeauserIdonthaveprivilleges,alsoIdontknowhowtomakeprivilegeswhenevenIdonthaveoneuser!mysql>CREATEUSER'parsa'@'localhost'IDENTIFIEDBY'parsa';ERROR1227(42000):Accessdenied;youneed(atleastoneof)theCREATEUSERprivilege(s)forthisoperation

    Itriedtosigninasroot:mysql>mysql-uroot-p;ERROR1064(42000):YouhaveanerrorinyourSQLsyntax;checkthemanualthatcorrespondstoyourMySQLserverversionfortherightsyntaxtousenear'mysql-uroot-p'atline1mysql>mysql-uroot-proot;

    http://stackoverflow.com/u/849530http://stackoverflow.com/q/8571928http://stackoverflow.com/u/1101134https://dev.mysql.com/doc/refman/5.0/en/distinct-optimization.htmlhttp://stackoverflow.com/q/8838777

  • ERROR1064(42000):YouhaveanerrorinyourSQLsyntax;checkthemanualthatcorrespondstoyourMySQLserverversionfortherightsyntaxtousenear'mysql-uroot-proot'atline1

    Tags:mysql(PrevQ)(NextQ)

    User:nickool

    Answer bynowhy

    No,youshouldrunmysql-uroot-pinbash,notattheMySQLcommand-line.Ifyouareinmysql,youcanexitbytypingexit.

    Tags:mysql(PrevQ)(NextQ)

    Q:Howtogetthesizesofthetablesofamysqldatabase?

    Tags:mysql(PrevQ)(NextQ)

    Icanrunthisquerytogetthesizesofalltablesinamysqldatabase:showtablestatusfrommyDatabaseName;

    Iwouldlikesomehelpinunderstandingtheresults.Iamlookingfortableswiththelargestsizes.

    WhichcolumnshouldIlookat?

    Tags:mysql(PrevQ)(NextQ)

    User:jpashs

    Answer bychapmic

    Youcanusethisquerytoshowthesizeofatable(althoughyouneedtosubstitutethevariablesfirst):SELECTtable_nameAS`Table`,round(((data_length+index_length)/1024/1024),2)`SizeinMB`FROMinformation_schema.TABLESWHEREtable_schema="$DB_NAME"ANDtable_name="$TABLE_NAME";

    orthisquerytolistthesizeofeverytableineverydatabase,largestfirst:SELECTtable_schemaas`Database`,table_nameAS`Table`,round(((data_length+index_length)/1024/1024),2)`SizeinMB`FROMinformation_schema.TABLESORDERBY(data_length+index_length)DESC;

    Answer bysumith-harshanSELECTTABLE_NAMEAS"TableName",table_rowsAS"QuantofRows",ROUND((data_length+index_length)/1024,2)AS"TotalSizeKb"FROMinformation_schema.TABLES

    http://stackoverflow.com/u/974380http://stackoverflow.com/q/8839017http://stackoverflow.com/u/1136992http://stackoverflow.com/q/9620198http://stackoverflow.com/u/1121218http://stackoverflow.com/q/9620273http://stackoverflow.com/u/1242826http://stackoverflow.com/q/12439645http://stackoverflow.com/u/885226

  • WHEREinformation_schema.TABLES.table_schema='YOURSCHEMANAME/DATABASENAMEHERE'LIMIT0,30

    Youcangetschemanamefrominformation_schema->SCHEMATAtable->SCHEMA_NAMEcolumn

    AdditionalYoucangetsizeofthemysqldatabasesasfollowing.SELECTtable_schema"DBName",Round(Sum(data_length+index_length)/1024/1024,1)"DBSizeinMB"FROMinformation_schema.tablesGROUPBYtable_schema;

    ResultDBName|DBSizeinMB

    mydatabase_wrdp39.1information_schema0.0

    Youcangetadditionaldetailsinhere.

    Tags:mysql(PrevQ)(NextQ)

    Q:WhatdoesitmeanwhenMySQLisinthestateSendingdata?

    Tags:mysql(PrevQ)(NextQ)

    WhatdoesitmeaniftheMysqlquery:SHOWPROCESSLIST;

    returnsSendingdataintheStatecolumn?

    IimagineitmeansthequeryhasbeenexecutedandMySQLissendingresultDatatotheclientbutImwonderingwhyitstakingsomuchtime(uptoanhour).

    Thankyou.

    Tags:mysql(PrevQ)(NextQ)

    User:user1345414

    Answer byquassnoi

    Thisisquiteamisleadingstatus.Itshouldbecalledreadingandfilteringdata.

    ThismeansthatMySQLhassomedatastoredonthedisk(orinmemory)whichisyettobereadandsentover.Itmaybethetableitself,anindex,atemporarytable,asortedoutputetc.

    Ifyouhavea1Mrecordstable(withoutanindex)ofwhichyouneedonlyonerecord,MySQLwillstilloutputthestatusassendingdatawhilescanningthetable,despitethefactithasnotsentanythingyet.

    Tags:mysql(PrevQ)(NextQ)

    http://webexplorar.com/how-can-i-get-database-table-sizes/http://stackoverflow.com/q/10347193http://stackoverflow.com/u/1345414http://stackoverflow.com/q/10347999http://stackoverflow.com/u/55159

  • Q:ERROR2006(HY000):MySQLserverhasgoneaway

    Tags:mysql(PrevQ)(NextQ)

    IgetthiserrorwhenItrytosourcealargeSQLfile(abigINSERTquery).Skipcodeblockmysql>sourcefile.sqlERROR2006(HY000):MySQLserverhasgoneawayNoconnection.TryingtoreconnectConnectionid:2Currentdatabase:***NONE***

    ERROR2006(HY000):MySQLserverhasgoneawayNoconnection.TryingtoreconnectConnectionid:3Currentdatabase:***NONE***

    Nothinginthetableisupdated.Ivetrieddeletingandundeletingthetable/database,aswellasrestartingMySQL.Noneofthesethingsresolvetheproblem.

    Hereismymax-packetsize:+--------------------+---------+|Variable_name|Value|+--------------------+---------+|max_allowed_packet|1048576|+--------------------+---------+

    Hereisthefilesize:$ls-sfile.sql79512file.sql

    WhenItrytheothermethod$./mysql-uroot-pmy_db>>------------------------------------------------------------------------------------------------------^^^^^Unquotedfunction//----------------------------------------------------------------------------------------------------^^^^^^^^^^^^Single-quotedDATE//-----------------------------------------------------------------------------------^^^^^^^^^^^^^^^Single-quotedstrings//-----------------------------------------------------------------------------^^^^^Unquotedkeyword//--------------------------^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^Backticktable&column

    Variableinterpolation

    Thequotingpatternsforvariablesdonotchange,althoughifyouintendtointerpolatethevariablesdirectlyinastring,itmustbedouble-quotedinPHP.JustmakesurethatyouhaveproperlyescapedthevariablesforuseinSQL.(ItisrecommendedtouseanAPIsupportingpreparedstatementsinstead,asprotectionagainstSQLinjection).//Samethingwithsomevariablereplacements//Here,avariabletablename$tableisbacktick-quoted,andvariables//intheVALUESlistaresingle-quoted$query="INSERTINTO`$table`(`id`,`col1`,`col2`,`date`)VALUES(NULL,'$val1','$val2','$date')";

    Preparedstatements

    http://stackoverflow.com/u/1101095http://stackoverflow.com/q/11321508http://stackoverflow.com/u/541091http://dev.mysql.com/doc/refman/5.5/en/reserved-words.html

  • Whenworkingwithpreparedstatements,consultthedocumentationtodeterminewhetherornotthestatementsplaceholdersmustbequoted.ThemostpopularAPIsavailableinPHP,PDOandMySQLi,expectunquotedplaceholders,asdomostpreparedstatementAPIsinotherlanguages://PDOexamplewithnamedparameters,unquoted$query="INSERTINTO`table`(`id`,`col1`,`col2`,`date`)VALUES(:id,:col1,:col2,:date)";

    //MySQLiexamplewith?parameters,unquoted$query="INSERTINTO`table`(`id`,`col1`,`col2`,`date`)VALUES(?,?,?,?)";

    Charactersrequringbacktickquotinginidentifiers:

    AccordingtoMySQLdocumentation ,youdonotneedtoquote(backtick)identifiersusingthefollowingcharacterset:

    ASCII:[0-9,a-z,A-Z$_](basicLatinletters,digits0-9,dollar,underscore)

    Youcanusecharactersbeyondthatsetastableorcolumnidentifiers,includingwhitespaceforexample,butthenyoumustquote(backtick)them.

    Answer bysalman-a

    TherearetwotypesofquotesinMySQL:

    1. 'forenclosingstringliterals2. `forenclosingidentifierssuchastableandcolumnnames

    Andthenthereis"whichisaspecialcase.Itcouldbeusedforoneofabove-mentionedpurposesatatimedependingonMySQLserverssql_mode :

    1. Bydefaultthe"charactercanbeusedtoenclosestringliteralsjustlike'2. InANSI_QUOTES modethe"charactercanbeusedtoencloseidentifiersjustlike`

    Thefollowingquerywillproducedifferentresults(orerrors)dependingonSQLmode:

    SELECT"column"FROMtableWHEREfoo="bar"

    ANSI_QUOTESdisabled

    Thequerywillselectthestringliteral"column"wherecolumnfooisequaltostring"bar"

    ANSI_QUOTESenabled

    Thequerywillselectthecolumncolumnwherecolumnfooisequaltocolumnbar

    Whentousewhat

    Isuggestthatyouavoidusing"sothatyourcodebecomesindependentofSQLmodes

    http://dev.mysql.com/doc/refman/5.5/en/identifiers.htmlhttp://stackoverflow.com/q/14123649http://stackoverflow.com/u/87015http://dev.mysql.com/doc/refman/5.6/en/sql-mode.htmlhttp://dev.mysql.com/doc/refman/5.6/en/sql-mode.html#sqlmode_ansi_quotes

  • Alwaysquoteidentifierssinceitisagoodpractice(quiteafewquestionsonSOdiscussthis)

    Tags:mysql(PrevQ)(NextQ)

    Q:CastfromVARCHARtoINT-MySQL

    Tags:mysql(PrevQ)(NextQ)

    MyCurrentDataforSELECTPROD_CODEFROM`PRODUCT`

    isPROD_CODE25782210911

    Ihavetriedallthefourqueriesandnonework.(Ref )SELECTCAST(PROD_CODE)ASINTFROMPRODUCT;

    SELECTCAST(PROD_CODEASINT)FROMPRODUCT;

    SELECTCAST(PROD_CODE)ASINTEGERFROMPRODUCT;

    SELECTCAST(PROD_CODEASINTEGER)FROMPRODUCT;

    Allthrowsyntaxerrorssuchasbelow:

    YouhaveanerrorinyourSQLsyntax;checkthemanualthatcorrespondstoyourMySQLserverversionfortherightsyntaxtousenear)ASINTFROMPRODUCTLIMIT0,30atline1

    YouhaveanerrorinyourSQLsyntax;checkthemanualthatcorrespondstoyourMySQLserverversionfortherightsyntaxtousenearINTEGER)FROMPRODUCTLIMIT0,30atline1

    WhatistherightsyntaxtocastvarchartointegerinMySQL?

    MySQLVersion:5.5.16

    Tags:mysql(PrevQ)(NextQ)

    User:emaillenin

    Answer byeggyal

    AsdescribedinCastFunctionsandOperators :

    Thetypefortheresultcanbeoneofthefollowingvalues:

    http://stackoverflow.com/q/12126991http://dev.mysql.com/doc/refman/5.5/en/cast-functions.html#function_casthttp://stackoverflow.com/u/184184http://stackoverflow.com/q/12127022http://stackoverflow.com/u/623041http://dev.mysql.com/doc/en/cast-functions.html#function_cast

  • BINARY[(N)]CHAR[(N)]DATEDATETIMEDECIMAL[(M[,D])]SIGNED[INTEGER]TIMEUNSIGNED[INTEGER]

    Therefore,youshoulduse:SELECTCAST(PROD_CODEASUNSIGNED)FROMPRODUCT

    Tags:mysql(PrevQ)(NextQ)

    Q:ERROR:Error1005:Cantcreatetable(errno:121)

    Tags:mysql(PrevQ)(NextQ)

    ImhavingtroubleswithforwardengineeringmyMySQLdatabaseintoWAMPserver..Iwasgoingtopostanimageoftheschemabutasthisismyfirstposticant..

    Belowistheexecutedscript..Skipcodeblockuseaquaticstar;

    SET@OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS,UNIQUE_CHECKS=0;SET@OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS,FOREIGN_KEY_CHECKS=0;SET@OLD_SQL_MODE=@@SQL_MODE,SQL_MODE='TRADITIONAL,ALLOW_INVALID_DATES';

    -----------------------------------------------------Table`Students`-----------------------------------------------------DROPTABLEIFEXISTS`Students`;

    CREATETABLEIFNOTEXISTS`Students`(`id`VARCHAR(10)NOTNULL,`studentName`VARCHAR(45)NOTNULL,`gender`CHARNOTNULL,`birthDate`DATETIMENOTNULL,`mNo`VARCHAR(10)NOTNULL,`contactName`VARCHAR(45)NOTNULL,`contactEmail`VARCHAR(45)NOTNULL,`contactPhone`INT(10)NOTNULL,`startDate`DATETIMENOTNULL,`remarks`VARCHAR(200)NULL,PRIMARYKEY(`id`))ENGINE=InnoDB;

    -----------------------------------------------------Table`WaitingList`-----------------------------------------------------DROPTABLEIFEXISTS`WaitingList`;

    CREATETABLEIFNOTEXISTS`WaitingList`(`wait_id`VARCHAR(5)NOTNULL,`name`VARCHAR(45)NULL,`contactName`VARCHAR(45)NULL,`contactPhone`INT(10)NULL,`contactEmail`VARCHAR(45)NULL,`status`CHARNULL,`remarks`VARCHAR(200)NULL,PRIMARYKEY(`wait_id`))ENGINE=InnoDB;

    -----------------------------------------------------Table`Schedule`-----------------------------------------------------

    http://stackoverflow.com/q/12623651

  • DROPTABLEIFEXISTS`Schedule`;

    CREATETABLEIFNOTEXISTS`Schedule`(`lesson_id`VARCHAR(10)NOTNULL,`day`VARCHAR(3)NOTNULL,`branch`VARCHAR(30)NOTNULL,`level`VARCHAR(30)NOTNULL,`time`TIMENOTNULL,`ae`VARCHAR(45)NOTNULL,PRIMARYKEY(`lesson_id`))ENGINE=InnoDB;

    -----------------------------------------------------Table`Link`-----------------------------------------------------DROPTABLEIFEXISTS`Link`;

    CREATETABLEIFNOTEXISTS`Link`(`link_id`VARCHAR(10)NOTNULL,`id`VARCHAR(10)NOTNULL,`lesson_id`VARCHAR(10)NOTNULL,PRIMARYKEY(`link_id`),INDEX`id_idx`(`id`ASC),INDEX`lesson_id_idx`(`lesson_id`ASC),CONSTRAINT`id`FOREIGNKEY(`id`)REFERENCES`Students`(`id`)ONDELETENOACTIONONUPDATENOACTION,CONSTRAINT`lesson_id`FOREIGNKEY(`lesson_id`)REFERENCES`Schedule`(`lesson_id`)ONDELETENOACTIONONUPDATENOACTION)ENGINE=InnoDB;

    -----------------------------------------------------Table`Attendance`-----------------------------------------------------DROPTABLEIFEXISTS`Attendance`;

    CREATETABLEIFNOTEXISTS`Attendance`(`date`DATETIMENOTNULL,`attendance`VARCHAR(5)NOTNULL,`link_id`VARCHAR(10)NOTNULL,INDEX`link_id_idx`(`link_id`ASC),CONSTRAINT`link_id`FOREIGNKEY(`link_id`)REFERENCES`Link`(`link_id`)ONDELETENOACTIONONUPDATENOACTION)ENGINE=InnoDB;

    SETSQL_MODE=@OLD_SQL_MODE;SETFOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS;SETUNIQUE_CHECKS=@OLD_UNIQUE_CHECKS;-----------------------------------------------------Datafortable`Students`-----------------------------------------------------STARTTRANSACTION;INSERTINTO`Students`(`id`,`studentName`,`gender`,`birthDate`,`mNo`,`contactName`,`contactEmail`,`contactPhone`,`startDate`,`remarks`)VALUES('s001','SamKhew','m','12/12/1991','nm','MayKhew','[email protected]',0198829387,'12/07/2011',NULL);INSERTINTO`Students`(`id`,`studentName`,`gender`,`birthDate`,`mNo`,`contactName`,`contactEmail`,`contactPhone`,`startDate`,`remarks`)VALUES('s002','JoeBiden','m','13/03/2003','nm','LaylaBiden','[email protected]',0199283763,'14/05/2011',NULL);INSERTINTO`Students`(`id`,`studentName`,`gender`,`birthDate`,`mNo`,`contactName`,`contactEmail`,`contactPhone`,`startDate`,`remarks`)VALUES('s003','BobBuilder','m','14/02/2002','LK920K','MamaBuilder','[email protected]',0167728376,'29/02/2012',NULL);INSERTINTO`Students`(`id`,`studentName`,`gender`,`birthDate`,`mNo`,`contactName`,`contactEmail`,`contactPhone`,`startDate`,`remarks`)VALUES('s004','KennyKoh','m','18/02/1999','MM992','LisaKoh','[email protected]',0123160231,'19/01/2012',NULL);INSERTINTO`Students`(`id`,`studentName`,`gender`,`birthDate`,`mNo`,`contactName`,`contactEmail`,`contactPhone`,`startDate`,`remarks`)VALUES('s005','JaneDoe','f','29/09/1999','nm','JackieDoe','[email protected]',0127736254,'02/03/2012',NULL);INSERTINTO`Students`(`id`,`studentName`,`gender`,`birthDate`,`mNo`,`contactName`,`contactEmail`,`contactPhone`,`startDate`,`remarks`)VALUES('s006','LolaLai','f','02/05/2004','nm','MarkLai','[email protected]',0198827365,'11/09/2011',NULL);

    COMMIT;-----------------------------------------------------Datafortable`Schedule`-----------------------------------------------------STARTTRANSACTION;INSERTINTO`Schedule`(`lesson_id`,`day`,`branch`,`level`,`time`,`ae`)VALUES('sat1_s4','Sat','Sunway','basic','4pm','Aini');INSERTINTO`Schedule`(`lesson_id`,`day`,`branch`,`level`,`time`,`ae`)VALUES('sat1_s5','Sat','Sunway','basic','5pm','Aini');INSERTINTO`Schedule`(`lesson_id`,`day`,`branch`,`level`,`time`,`ae`)VALUES('sat1_s6','Sat','Sunway','basic','6pm','Aini');INSERTINTO`Schedule`(`lesson_id`,`day`,`branch`,`level`,`time`,`ae`)VALUES('sat2_s4','Sat','Sunway','advance','4pm','Nina');INSERTINTO`Schedule`(`lesson_id`,`day`,`branch`,`level`,`time`,`ae`)VALUES('sat2_s5','Sat','Sunway','advance','5pm','Nina');INSERTINTO`Schedule`(`lesson_id`,`day`,`branch`,`level`,`time`,`ae`)VALUES('sat3_s6','Sat','Sunway','pre-comp','6pm','Marcus');

    COMMIT;-----------------------------------------------------Datafortable`Link`-----------------------------------------------------STARTTRANSACTION;

  • INSERTINTO`Link`(`link_id`,`id`,`lesson_id`)VALUES('L001','s001','sat1_s4');INSERTINTO`Link`(`link_id`,`id`,`lesson_id`)VALUES('L002','s002','sat1_s5');INSERTINTO`Link`(`link_id`,`id`,`lesson_id`)VALUES('L003','s003','sat1_s6');INSERTINTO`Link`(`link_id`,`id`,`lesson_id`)VALUES('L004','s004','sat2_s4');INSERTINTO`Link`(`link_id`,`id`,`lesson_id`)VALUES('L005','s005','sat1_s5');

    COMMIT;--------------------------------------------