dimanche 31 juillet 2016

How to insert data into Parse table by using PHP code

How to send data from PHP file to Parse.com table ?

How do I model a database for an e-commerce website using MySQL? [on hold]

How do I model a database for an e-commerce website using MySQL?

What is a Covered Index?

I've just heard the term covered index in some database discussion - what does it mean?

Mariadb replication with active-active mode?

Does anyone give me the configuration of active-active masters and a slave gtid replication with mariadb.

what is the use of outer join as it combines all the records from both the tables?

what is the use of outer join as it combines all the records from both the tables?

How to reset AUTO_INCREMENT in MySQL?

How can I reset the auto-increment of a field? I want it to start counting from 1 again.

What is the application of Embedded SQL? or in specific Pro C?

I am not sure about the application. Probably this is old? Is there any alternative to it?

Picture file to sql data type BLOB on Android [on hold]

How to convert an image file to blob and insert it with rawQuery into the database on Android?

How to Script Automatically, the securables assigned to a SQL account

I want to generate script to assign an user account to some securables, e.g. Table:Select. How to do this?

MYSQL Order By For Azerbaijan Alphabet

I want to sort my column using Azerbaijan alphabet in Mysql. What is the best way to do it?

Algebra Relational sql GROUP BY SORT BY ORDER BY

I wanted to know what is the equivalent in GROUP BY, SORT BY and ORDER BY in algebra relational ?

How to make a php form readonly after submission and editable on the same page clicking on edit?

How to make a php form readonly after submit and editable on the same page once clicking on edit.

Show datatables.net in bootstrap modal dialog box

When i'm using data table in modal dialog box , its functions like page showing entries and search box stops working.

What is wrong with my SQL Query

What is wrong with my query? SELECT * FROM table WHERE name LIKE 'foo%' AND WHERE itemType = '1' ORDER BY endTime ASC LIMIT 0

Why by choosing data range from the last year I only get values for this year? How to manipulate a data ranges?

select AccountingDate from Test_Plaza_ProductionReport where AccountingDate >='2015/06/24' AND AccountingDate <= '2016/06/24 23:59:59.999' And My Accounting Date only in 2016, whats with 2015?

Connecting MySQL with Visual Studio C#

I'm new to MySQL Workbench and I'm trying to make a Timekeeping system. I'm wondering how to connect MySQL with Visual Studio C#?

ON DELETE CASCADE on sql developer tools

I'm using sqldeveloper 4.1.3.20.78 tools. I can't find any option of ON DELETE CASCADE in GUI. Is that option available? I'm using oracle 10g.

How to check if any cell in a row is 0 with PHP and mysql

The title says it all. I want to say "SELECT * FROM info WHERE id = 1" and if any cell besides id, is 0 I want to do something.

How to select parent child 'n' th records without recursion in sql?

id | name | parent_id ----+--------------+----------- 1 | Cat |
2 | Fun | 1 3 | LOLCs | 2 4 | Anid | 2 5 | Cla | 1 6 | Rena | 5 ................................. Up to 'N' th Level

Pls help me...

samedi 30 juillet 2016

Count work days between two dates

How can I calculate the number of work days between two dates in SQL Server?

Monday to Friday and it must be T-SQL.

Convert YYYYMM to MMMYY

I have a period 201604 (nvarchar). I am wondering is there a way that I can convert 201604 to APR16? Help will be appreciated!

Constant column value in MySQL table

I have a table in MySQL. I'd like to set a column value for a table to be a constant integer. How can I do this?

Prepend (add character) to string in sql server

I have a column in a sql table called ID (ex. 1234,12345) I want to add a "LM" to every record in that column. LM1234, LM12345, etc

Use of Non clustered Indexes

I know the differences between clustered and non-clustered indexes. Can someone tell me the various scenarios where we actually prefer non clustered index over a clustered index ?

useLegacyAuth=1 in MySQL Workbench 6.3 (Win x64) fails with Wrong type passed, expected sql::SQLString

There's no way to make this work.

I tried all kind of combinations, all failing.

useLegacyAuth=1
useLegacyAuth="1"
useLegacyAuth='1'
useLegacyAuth=`1`

Install Mysl Server & phpmyadmin & php on ubuntu 16.04 [on hold]

I want to install php server for php development at ubuntu 16.04. I am facing error when I install php server and mysql and phpmyadmin. Please help me...

how to query record with multiple condition using yii framework

I want to get all the results satisfy (age=20, name=jim) or (age=30, name=allen) or (age=40, name=sam), how to write the query code with yii?

Netezza get records last updated in last 5 minutes using a last modified time stamp column in the table?

How to select records that updated in last 5 minutes using a last_modified_timestamp column in the table using current_date or current_timestamp function in Netezza?

Mysql - INSERT INTO table IF table exists otherwise CREATE TABLE

Do mysql support something like this?

INSERT INTO `table` VALUES (NULL,"1234") IF TABLE EXISTS `table` ELSE CREATE TABLE `table` (id INT(10), word VARCHAR(500));

Generate sql insert script from excel worksheet

I have a large excel worksheet that I want to add to my database.

Can I generate an SQL insert script from this excel worksheet?

phpmyadmin query not executing

on executing query on phpmyadmin. a small dialog box appear and disappear for a second, and no response i get.
please help me to solve the problem

Cant make my query work mysql PHP [on hold]

I can not make my query works can anyone knows whats wrong! Thanks.

select * from coments where publicacionID="245" id < 177 order by id asc limit 5

Rails: How to filter records created between two times of the day regardless of the date?

I would like to filter records created between two certain times of the day regardless of the date. For example all the records created between 02:00 and 13:00 on any day.

Insert datatable into existing Access file

I want to select content from an existing SQL Server and store the Information in an existing Access file. How can i easily update the table in my file?

MySQL Datatype for storing bloodtype?

Which MySQL datatype would be preferable (the smallest amount of data needed) for storing blood types? In other words, storing one to two letters with the '+' or '-' symbol. Thanks

Use Ruby database on Rails [on hold]

I created a mysql database with Ruby. I want to use it on my Rails app. How can I do it? How can I read data with Rails without any database?

Computed Column in Mysql

I am trying to add a computeed column.

alter table datatest add column amount2 double  as (amount*rate)

but I got error while executing this

mssql from databases

All software I'll need. All hardware I'll need. All coding languages I'll need to know. Other skills that I'll need. Please add anything in addition to these points of information for mssql

Database for applicant tracking system [on hold]

I am designing database for applicant tracking system in sql.Ihave kept tables for candidate,recruiter and client.Should I also keep table for resume.If yes what should be the fields?

Discover collation of a MySQL column

I previously created a MySQL table and now I want to find out what collation some of the fields are using. What SQL or MySQL commands can I use to discover this?

Cast DateTime column value in to DD MM YYYY hh:mm:ss:SSS format in SQL

I want to convert to current datetime format into "DD MM YYYY hh:mm:ss:SSS", is there any logic that I need to write or any predefined variable exist in SQL.

How can I check how often a replication agent is executed?

Is it possible to check (in an existing replication) how often the replication agent is executed? (For example every 5 minutes, every 2 weeks,...)

I can't find it in the SQL-Server Agent.

vendredi 29 juillet 2016

Why shouldn't I use mysql_* functions in PHP?

What are the technical reasons why I shouldn't use mysql_* functions? (e.g. mysql_query(), mysql_connect() or mysql_real_escape_string())? Why should I use something else even if they work on my site?

Run multiple/all sql files and show error log file

How to run all SQL files in a directory and display the error of the script you execute if there is an error, how will you log or record the error upon running?

Convert MDDYYYY and MMDDYYYY column to MM-DD-YYYY in Oracle SQL

I used SELECT TO_DATE(INC_DATE, 'MMDDYYYY') FROM BASICINCIDENT2010;but since not all the dates in the inc_date are of the same format. It causes the error of Month not found.

How could i search age from database birth day field?

I want to find age from mysql database field name birthday. Ex. if anyone's data of birth is 25-07-1991 then i want to query his present age from mysql database. please someone help me.

How to store images in mysql and retrieve and display them through jsp

i am working with jdbc,mysql,html,jsp.i want to store an image into database through jdbc code and retrive and display them using jsp.please help urgently.I'm creating an online shopping website as a project.

Insert a looping data into database using PHP

I have a looping data and would like to insert it into another table.Somehow, I have tried some codes, but didn't work on it. Can someone show me how to insert it. I really need your helps.

filter repeating fields without using DISTINCT in sql server

query

how to filter repeating fields without using DISTINCT in sql server?

XML MYSQL realtime sync

I want to update my mysql database realtime (every 1-3 sec) from xml dates. What is the best way for it? Write a PHP script what I called every second, or is there a better way?

How to set IntelliJ IDEA View to see SQL query result and explain plainat the same time?

is there any way to configure Intellij to show SQL query result (tables) in one tab, and at the same time the query explain plan in other tab? I mean simple sql query like: select * from whatever;

MySQL Query students that studied for all the schools

Table consists of School_id and Student_name.

School_id   Student_Name
1           Raj
1           Tan
1           Brian
2           Raj
2           Brian
3           Raj
3           Tan

So the output should be Raj, as Raj has studied in all schools(1,2,3).

Connecting RestAPI Slim framework to Android application

I am new Android Developer, and I am trying to connect MySQL throw the application with Rest API that connected by Slim framework, so can you please explain how to connect the Php file from the Slim framework.

I want to make a quiz for my WebSite

I want to make a quiz for my WebSite. Ask 1 Questin and Answers, and the Resultat come to me. I don't now very much about HTML, MySQL and PHP i am asking you if you can Help me...

What is the application of Embedded SQL? or in specific Pro C? [on hold]

What is the current application this Embedded SQL is used? For eg: SQL could be used with Java, there are frameworks like Spring. What is the advantage we get from it? What is the peculiarity of this language?

Group BY Does Not Work?

I want to group some rows in sql during fetch with WHERE Condition But it does not work ? $query2 = connection()->query("SELECT * FROM issue WHERE issue_id='".$row1["issue_no"]."' GROUP BY volume_id"); Please Help this

How to insert a line break in a SQL Server VARCHAR/NVARCHAR string

I didn't see any similar questions asked on this topic, and I had to research this for something I'm working on right now. Thought I would post the answer for it in case anyone else had the same question.

Using a variable to name query results column

Is there a way to use a variable to name a column in SQL query results? My example below gives an "Incorrect syntax" error?

declare @ColumnName varchar(100) = 'Column 1'

Select CustomerNumber as @ColumnName
  from Customers

How to call function from function in sql

create FUNCTION [dbo].[fun1] 
(   
    @ID int
)
RETURNS TABLE 
AS
RETURN 
(
    declare @var int
select @var =select columnName from dbo.fun2(@id)
    SELECT @var* columnName  from
    table
    where table.id=@ID

)

How can I do it?

disable or drop the index in ETL stage load

The T-SQl procedure truncate a stage table and insert data into the stage table.What is the best deign pattern to follow in this ETL stored procedures

disable and enable the index or drop and recreate the index

JAX-RS to MYSQL connection?

I have a simple Java EE application, writen with REST services and I`m using JAX-RS server, but I want to connect it to my MYSQL database, so my qustion is how can I connect JAX-RS server to MYSQL database ?

Eclipse - How to add a new MariaDB connection

How can I add a new MariaDB connection to eclipse? I am using the Data Source Explorer view, however when I try to create a new database connection there are connections for MySQL, Oracle, Informix... but no for MariaDB. Can anyone help me?

How to take Bitnami-orange Hrm mysql database backup

from Bitnami we have installed orange HRM in localhost ,now i need to take mysql back up means mysql export(exampe.sql file) Here i checked phpmyadmin not there can u tell me how we can take out mysql databack up.

Composite Unique Constraint SQL

I have a table with parents and children, each record has a PRIMARY KEY id, a 'name', and a 'parent' that references another record's 'id'.

Can I enforce UNIQUE constraint on the 'name' among records that share a 'parent'?

how to write SUM with Group by clause in SQL

SUM with Group by clause not working....

 $totdueamt=mysql_fetch_array(mysql_query("SELECT SUM(due_amount) as duedam FROM payments where branch='$duebid' and `due_date_bc` between '$frmdtdue' and '$todatdue' group by enq_id")); 

SQL Partition Dates

I have data such as this: ID|From Date |To Date 1 |01/01/2014 |04/01/2015 1 |04/01/2015 |01/01/2016 1 |01/01/2016 |12/31/2016 But I would like this as the end result: ID|From Date |To Date 1 |01/01/2014 |12/31/2016 I tried partitioning, but I'm not quite familiar with how it works. Any suggestions would be greatly appreciated. Thanks!

jeudi 28 juillet 2016

Talend-error-capturing

How to capture failed records(example foreign key contraint/parent table not found/unique key Constraint etc)???? After capturing those failed records I need to send an email notification along with count of failed records and message to why that records failed..??

Using multiple joins in

there is a good way to do multiple joins in one Query?

I did not tried before to do more than one Join in Query and I hope there is be nice & genteel way for doing it.

thanks!!

Finding Members between a Date Range

I need to find Membership between two dates ( 7-01-14 and 6-30-15) who have been members at least 4 months or more during that time frame.There is a START_DATE and an END_DATE column. Any advice would be appreciated. Thank you.

MySQL Insert performance degrades on a large table dued to the size of the primary key

Could the INSERTs be slow, dued to the size of the PRIMARY KEY?

We are using hash algorithm to generate the primary key for the table into DB.

For example: 178E1775000064A71F7B413AAFDBBE24BD93650D- Primary Key

Select last row in MySQL

How can I SELECT the last row in a MySQL table?

I'm INSERTing data and I need to retrieve a column value from the previous row.

There's an auto_increment in the table.

Extract XML data from Hive Table and Parse the data

I want to extract particular column values from a hive table. That column has XML data. How to parse through XML data and extract name and values from that particular XML column. Also I want to insert the extracted data into another Hive table.

mysql query concatination error

can anyone tell me what is the wrong with the query

$sql = "SELECT * FROM user_monsoon_offer WHERE DATE_ADD(start_date,INTERVAL 4 DAY) = ' ".$date." ' AND user_monsoon_offer.user_id NOT IN (SELECT user_id FROM transactions)";

adding an autoincrement field in mySQL with prefix

I want to add an auto increment field in one of the columns in MySQL which will act as the primary key of my table.I saw the post which describes how to do this using triggers. Is there any other way to do this?

images are not displaying in asp.net webform

i have image links of a website's images stored in my DB but when i show them on my asp page using repeater or data list which im building, it shows some where pics and somewhere just boxes and no image, can anyone help me?

Error in importing MySQL connector in Python 3.5

I am getting ImportError: No module named 'mysql' while I do the following...

>>> import mysql.connector

MySQL is installed and am on Python 3.5. I can't figure out. The above command is running fine in Python 2.7.

Write the query without Temp

But I need simple way using joins

DECLARE @ID uniqueidentifier
    SELECT @ID ='000000910035';
    WITH temp AS(

            SELECT  *
            FROM    BB
            WHERE   MId =  @ID
            UNION ALL
            SELECT  t.*     FROM    BB t INNER JOIN temp r ON t.PaId = r.MId
    )

    SELECT  *
    FROM    temp

Select WHERE Cast - Maintain Order

I am trying to maintain the order of the fields here. Any thoughts? This produces a result, but the results come out in varying order.

SELECT value FROM field_one WHERE cast(field_number as BINARY(6)) IN

(44,121.3,121.6,77,78,3,2.1,2.3,2.4,2.5) AND lead_id=1234 AND form_id=123

Mysql Insert from another table and count records

I want to to how many 'users' will be inserted into 'ladder'

Thats what i got:

INSERT INTO ladder (id, text, createdAt)
    SELECT id, text, createdAt
    FROM users
    WHERE invisible=0
    AND createdAt >= $today
    LIMIT $maxValue

Thanks for help:)

POST JSON data from iOS to mssql Server [closed]

Can someone please tell me what is the best way to create web service that sends JSON to MS SQL server.(php or .net POST web service?) I want to host the web service on IIS if possible.Links of tutorials will be very useful. Many Thanks.

Unwind array values in BigQuery/SQL

I was trying to unwind array values to different rows in BigQuery/ PSQL. This is what I have right now :: Col_1 col_2 A array: {1,2,3,4,5} B array: {1,2,3} C array: {4,5,6} I want to convert this as shown below in BigQuery. A 1 A 2 A 3 A 4 A 5 B 1 B 2 B 3 C 4 C 5 C 6

Send images over WhatsApp (Automatically with root) on Android

My main problem is the thumb_image column in the msgstore.db of whatsapp. Does anyone know how to generate this? It's a blob data type and I don't know what exactly has to be inserted in order to get it to work. Or is it even needed?

Something adds non-sence lines to my database (phpMyAdmin)

I've got a database and suddenly, something is adding lines of text into the database. I've got no clue what can cause that... And the message in the content stars with content" comment[number]" and than there are some links to some products... Can anyone help me please?

sql query in orange datamining software

When I am trying to run a SQL query in orange datamining software using select statement and postgres database, it returns an error

INVALID CONNECTION OPTION 'PASSWD'

My query looks like this:

select * from CFAR_K7_DBTF_ALL;

Date Conversion in SQL

I have a date in following format in my DB.

10/16 - mm/yy

I need to convert it to:

October/16

Is this possible?

If it's not possible then please tell me why.

Extract text to the left of the '-'

I am trying to get the data to the left of the - I tried the code below

LocationName
CCC-CC36-A
5N-N577-A
5N-N577-A
5N-N577-A
2T-225-A
PE-020-A

select 
LEFT(LocationName, LEN(LocationName) - CHARINDEX('-',LocationName)-1),
EncounterNumber
from #TubeRateQty

mysql get last 3 row and compare record

I have a table how can I get last 3 row to compare and get count number?

Example: table

id| name
=========
1 | Apple
2 | Orange
3 | Kiwi
4 | Banana
5 | Apple
6 | Banana
7 | Apple

How can I get Apple count number last 3 row?

Many thanks

How to Use Formula in SQL Query Dynamic?

I need your help to create query dynamically, how to populate data value from formula in other table.

Sample Below

Table A 
ID   Amount 
1    50 
2    40 
3    50 

Table B 
ID   FormulaID   VALUE 
X    1+2+3 
Y    1-2+3 

Result Expectation 
ID   FormulaID   VALUE 
X    1+2+3       140 
Y    1-2+3       60 

Thanks

How to Disable Strict SQL Mode on my Dedicated server?

How to disable Strict SQL Mode from my Cent OS 7.1 (64 Bit) Dedicated Server ?

I am a beginner and only know how to log in to SSH I wan't to disable it from SSH not phpmyadmin ?

Could you tell me the steps to enter on ssh !?

SQL query for extracting multiple rows with single date entry

I have a table "T" that contains Date as one of the column.

In the table, there are multiple rows associated with single date entry.

I want an query that will give me all the rows associated with the latest date available in the table.

mercredi 27 juillet 2016

Get month and year from a datetime in SQL Server 2005

I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?

Cannot find MySQL for MAC OS X 10.7.5 (Lion)

i went to the mysql website for downloading mysql community server for my mac os x lion but all of those there are for el capitan,mavericks and yosmite. i know there is a version for lion but i cant find so please give me a link to it.

How to fetch a dummy record if a sub-query count is zero?

I need to fetch one dummy record from tableA when the count of records in tableA is zero. If the table count is more than zero,then there should not be the dummy value X fetched. It is something like: Select 'X' As Count from tableA When (Select count (*) From tableA) >0

MySQL cluster error 1114 (HY000): The table 'users' is full

I have a MySQL cluster setup, There are 2 data nodes and 1 management node. We are now getting errors on our data nodes when doing inserts. ERROR 1114 (HY000): The table 'users' is full Please any help is appreciated, Is this a config issue, if so which node? each node is an Ubuntu 9 server.

Access denied for user in mysql database

i have a problem with my crud application in java with a database in mysql.My code seems to be right but when i run it(i'm speaking about an interface login) when i enter the right username and password and click login i have this error message : Access denied for user

how can I search json in mysql via medoo liberary?

I have a filed (section) in a mysql DB with this json content:

{"section2":"303","section1":"302","section0":"301"}

I use meedo lib DB.

how can I search secion1,section2,section3 in DB?

$database->select('Article', "*",[
                            "AND" => [
                            "section" => ?
                            ]
                       ])

                   )

Oracle + finding match between semicolon-separated columns

I have a table with two columns A and B where the values are semi colon separated. A has value 'a;b;c;d;e' B has value 'a;b;d;e' I want to check that if value in column B are all present in column A. Please guide me. Thanks !

Using Wildcards in SQL to delete part of a string

I am cleaning up addresses so I can compare them between two databases. I want to delete the word "apt/unit" and the apartment number/letter that follows.

Current vs. Desired

20951 VIA OLEANDER APT E = 20951 VIA OLEANDER

7623 SOUTHAMPTON TER UNIT 209 = 7623 SOUTHAMPTON TER

Distinct values from two columns

This is the query which I am using to get the distinct values:

SELECT DISTINCT
    LOGIN_BY,
    RECEIVED_BY
FROM SAMPLE

My requirement is I need the distinct values of both the columns as a single output. Is there any way to do that?

Parse.com Join two tables with one to many relationship

I have database at parse.com which have tables, Book and User. Book can have multiple authors defined as Relation field to User table.

I need to write a Parse query to fetch all books of specific author and I don't know how.

How do I find unique, non-English characters in a SQL script that has a lot of tables, scripts, etc. related to it?

I am getting a UnicodeDecodeError in my Python script and I know that the unique character is not in Latin (or English), and I know what row it is in (there are thousands of columns). How do I go through my SQL code to find this unique character/these unique characters?

Similar function to SQL where clause in R

I have a data set assigned to a variable named 'temps', which have columns 'date', 'temperature', 'country'.
I want to do something like this, which I can do in SQL

SELECT * FROM temps WHERE country != 'mycountry'

How can I do similar selection in R?

Importing in Google Cloud SQL

I was trying to import a big SQL file. Now I can see Importing... all the time when I open Google Cloud Console. The problem is that I cannot eliminate the instance or doing something because of it. I need to stop this process that has been active for more than 7 days.

SQL: Is it possible to calculate field by formula inside another field as text

Is it possible to make table or view, that have filed calculation by formula ,that specified in other field as text?

for example:

    A     B     C    formula    value
-   -     -     -   --------    -----
1.  2     1     3    (A+B)*C      9
2. 100   null   2      A/C       50

thanks and best regards

How to find out the MySQL root password

I cannot figure out my MySQL root password; how can I find this out? Is there any file where this password is stored?

I am following this link but I do not have directadmin directory in local.

Firebird query takes unusually long time to process

I am executing following query which contains 3000 conditions inside in operator.

select * from Orders a where a.key 
 in(101,155,16,45,778,9,8,67,1,44,455,56,88,888,8888,88888,77777,77,78, 3000) 

Number of numeric values inside in is 3000. This query is working very slow and sometimes it throws an exception. Is there any other way to write this query.

Mysql to Django Query Conversion

I have a MySQL query that I need help converting to Django

select * from TABLE where ID=10 group by LOCATION order by DATE DESC

Thus far I have TABLE.objects.filter(id='10').order_by('-date') but I am unsure how to do the group by in Django.

Search with "Hash sign" in Solr

I am new to Solr and facing problems while optimizing the search in solr. When i search for "C4902AN#140", it displays results with "140" first and result with ""C4902AN#140" is appearing later.i.e. after results containing "140".But I want result with "C4902AN#140" before results having "140".

Thanks in advance!!!

If I was creating a mashup of Instagram and Behance, what will I need to know? [on hold]

The information I think I need:

  1. All software I'll need.
  2. All hardware I'll need.
  3. All coding languages I'll need to know.
  4. Other skills that I'll need.

Please add anything in addition to these points of information if you think it is relevant.

Active record AND Operator

how do i turn this into one WHERE statement? I want to look for records where a property is an apartment and also is for sale.

def apartment
    @apartments_for_sale = Property.where(for_sale: true)
    @real_apartments = @apartments_for_sale.where(apartment: true)
end

Thanks a lot!

Date difference in days (excluding weekends/BigQuery)

I would like to get the exact amount of days between two timestamps (ex. 1.45 days). The thing is BigQuery datediff function rounds the day and only accepts 2 timestamp arguments. SELECT datediff(start_time_pac_tz, end_time_pac_tz) as Date_difference Date_difference -6 Also I'm looking to exclude weekends. Any help is greatly appreciated.

What does Connection.isValid(time) actually do to check if connection if valid?

Using OJDBC process does the isValid method use to check if the the connection is still alive? I'm trying to figure out what impact it could have on the database and how heavy this process is. e.g. does it request a column, or just ping the db with a couple bytes of data.

Difference between one to many and many to one relationship

What is the real difference between one to many and many to one relationship? It is only the 'vice-versa' kind of?

I can't find any 'good-and-easy-to-understand' tutorial about this topic other than this one: SQL for Beginners: Part 3 - Database Relationships

SQL query to select dates between two dates

I have a start_date and end_date. I want to get the list of dates in between these two dates. Can anyone help me pointing the mistake in my query.

select Date,TotalAllowance from Calculation where EmployeeId=1
             and Date between 2011/02/25 and 2011/02/27

Here 'Date' is a datetime variable.

mardi 26 juillet 2016

creating a sql table

I am trying to create my first SQL table and I am getting a syntax error and cannot figure out why. Here is my code:

create table ps 
(
  USER VARCHAR(20),
  PID INT(10),
  %CPU DECIMAL(4),
  %MEM DECIMAL(4),
  VSZ INT(10),
  RSS INT(10),
  TTY VARCHAR(10),
  STAT VARCHAR(5),
  START VARCHAR(20),
  TIME VARCHAR(20),
  COMMAND VARCHAR(20)
);

Can a SQL Stored Procedure drop itself and continue execution?

Specifically, can I do this?

CREATE PROC AutoDestructiveStoredProcedure
AS
DROP PROC AutoDestructiveStoredProcedure
PRINT 'Still alive.'
GO

Is it a bad practice?

What is the expected behavior? Does it change based on implementation? What would be the difference between executing this in SQL Server, MySQL and Oracle?

Doctrine Schema Create for just one Bundle

How do I tell Symfony to generate tables for just one Bundle?

Everytime I create a bundle and run:

php app/console doctrine:schema:create

It creates on my current database (of the specific bundle) ALL tables from ALL of my bundles. And I don't need that.

SQL Server error handling pattern

I am not an expert on SQl Server. Is this a valid pattern for handling errors in a batch of SELECT, INSERT...in SQl SERVER ? (I use v.2008)

BEGIN TRANSACTION
    BEGIN TRY
       -- statement 1
       -- statement 2
       -- statement 3
       COMMIT TRANSACTION
    END TRY

    BEGIN CATCH
       ROLLBACK TRANSACTION
    END CATCH

Thanks

how to validate the database by using logical formula?what is the sql query?

lets assume that i have database contain of one table "table1" contain of two columns col1 and col2 and i have this logical formula ¬∃a1 ∃a2 (¬table1(a1,c1)∨¬table1(a2,c2)∨ c1=c2) how to check if this formula can be satisfied by tables values? what is the SQL query?

Adding counts based on flags by dates

Could you please advise some direction on how to achieve the below format? I am at lost thinking solution for this problem. basically where flag is 0, sum it up and add it to the very next value where flag is 1 by date date: date hrs_clock some_flag some_count ================================================= 6/20/2016 1 0 5 6/20/2016 2 0 6 6/20/2016 3 1 4 6/20/2016 4 1 2 6/20/2016 5 0 4 6/20/2016 6 0 6 6/21/2016 1 0 4 6/21/2016 2 0 3 6/21/2016 3 1 7 6/21/2016 4 1 2 6/21/2016 5 0 5 6/21/2016 6 0 4 6/22/2016 1 0 5 6/22/2016 2 0 5 6/22/2016 3 1 3 6/22/2016 4 1 2 6/22/2016 5 0 8 6/22/2016 6 0 4 Result: date hrs_clock some_flag some_count ================================================= 6/20/2016 3 1 15 6/20/2016 4 1 2 6/21/2016 3 1 24 6/21/2016 4 1 2 6/22/2016 3 1 22 6/22/2016 4 1 2 6/22/2016 5 0 8 6/22/2016 6 0 4

SQL Server : setting language while creating view

I need to have months in my language in this view. I try this:

CREATE VIEW countTask
AS
    SET LANGUAGE Polish

    SELECT COUNT(*), DATENAME(Month, startdate), YEAR(startdate)
    FROM TBL_TASKS
    GROUP BY YEAR(startdate), DATENAME(Month, startdate)

but it's not correct. Do you know how can I fix it?

How to save and compare biometric fingerprint data in a php mysql project

I have a Codeigniter project. I want to integrate biometric device in it and save users fingerprint data into MySQL and later I have to compare that data. How can I do that? I mean how this process can be done and how to compare users data when they push his/her fingerprint on the device?

How do i find who got maximum % salary from employee table?

Here the emp table : To show the employee who got the maximum % salary between 01-jan-81 and 31-dec-81

  EMPNO ENAME             SAL HIREDATE
------- ---------- ---------- ---------
  7369 SMITH             800 17-DEC-80
  7499 ALLEN            1600 20-FEB-81
  7521 WARD             1250 22-FEB-81
  7566 JONES            2975 02-APR-81
  7654 MARTIN           1250 28-SEP-81
  7698 BLAKE            2850 01-MAY-81
  7782 CLARK            2450 09-JUN-81
  7788 SCOTT            3000 09-DEC-82
  7839 KING             5000 17-NOV-81
  7844 TURNER           1500 08-SEP-81
  7876 ADAMS            1100 12-JAN-83
  7900 JAMES             950 03-DEC-81
  7902 FORD             3000 03-DEC-81
  7934 MILLER           1300 23-JAN-82

PHP MYSQL sum subtotal

I have a problem, I want to sum up subtotal from invoice order, here's the picture: I wanna sum subtotal before add the shipping cost. I've tried $subtotal = ($subtotal + $totalcost); but didn't work foreach($rows as $row){ $totalsemua = 0; $foto = $row['foto']; $qty = $row['qty']; $name = $row['name_prod']; $price = $row['price']; $totalcost = $price*$qty; $subtotal = ($subtotal + $totalcost); ?> Anybody?

Trying to install adventureworks 2016 database

I am a newbie when it comes to sql server, and I am trying to install adventureworks 2016. I clicked on restoring databases, but I cannot find the .bak files, even though I have saved them. Do I need to save the .bak files in a specific place? And then how do I look for them to restore? Thank you!

Using MIN in where clause

Trying to change the following code to allow me to use min in where clause

SELECT od.personID
,'Uno' AS [CustomerType]
FROM dbo.orderDetails od
WHERE od.orderDate BETWEEN CONVERT(date, '2016-02-01') AND @StartDate
AND MIN(odd.orderDate) BETWEEN CONVERT(date, '2016-02-01') AND @StartDate)
GROUP BY personID

How can i Encryption mysql database data which i stored in openshift?

I use mysql in openshift site to store my android application database ,

However, i use json , netbeans to generate .war file , i want to Encryption database to protected it . my project in open shift contain : Tomcat7 , PHPmyadmin 4.0 , MySQL 5.5

is there any method to do Encryption between mysql in openshift and android java file ?

Undefined function mysql_connect()

I have ran aptitude install php5-mysql (and restarted MySQL/Apache 2), but I am still getting this error:

Fatal error: Call to undefined function mysql_connect() in /home/validate.php on line 21

phpinfo() says the /etc/php5/apache2/conf.d/pdo_mysql.ini file has been parsed.

SQL Server queries case sensitivity

I have this database:

abcDEF

ABCdef

abcdef

if I write: select * from MyTbl where A='ABCdef'

how to get: ABCdef

and how to get:

abcDEF

    ABCdef

    abcdef

Thanks in advance

forgot to write - sqlCE

MySQL multi source replication

Can somebody write me step by step how to make multi source replication. I read a lot of info about it but i have a problem with gtid-mode. I turn on gtid-mode in my.ini file on the master computer but when i make dump on databases i got error with gtid executed need to be empty.

odbc dsn settings doesn't get connected [odbc] [asterisk]

after configure odbc I get this things I can get database connecte

*CLI> odbc show

ODBC DSN Settings

Name: asteriskcdrdb DSN: MySQL-asteriskcdrdb Last connection attempt: 2016-06-13 12:39:25

Name: MySQL-elastix DSN: MySQL-elastix Last connection attempt: 2016-06-13 12:39:22

*CLI> odbc show statut

ODBC DSN Settings

retrieve data from database to textbox and changes made to the textbox should update in the database

I want to display data in textboxes with comparing username(SESSION variable) with table column name and edited changes should be updated.Please help. Table is given.and the php page also shown

Recovering corrupted tables

Our server was down by no reason and after we have recovered virtual machine disk and mounted it we realized that some MySQL tables are corrupted. Most of the tables are interconnected and this makes it important for us to recover every single corrupted table.

We have a big hurry, is there anyone to help us?

Sum SQL timestamp

How can do a sum search by 'id=1' and add up their hours. The first line will be there in time, the next will be their out time.

Below should add up to 5:43:29

id, ts
1,2016-06-20 04:25:32
3,2016-06-20 07:40:09
1,2016-06-20 09:37:46
3,2016-06-20 14:40:57
1,2016-06-20 15:12:14
1,2016-06-20 15:43:29
2,2016-06-20 15:47:01
2,2016-06-20 17:47:03

how do i fetch date timestamp as UTC

I am storing date timestamps in DB as UTC value, while retrieving it back i need to make as UTC time and need to convert to specific timezone value.

i.e. 2015-05-01 00:09:30:00 UTC time need to convert to IST(Or other timezone)

resultSet.getDate("VisitDate")

please help on this.

What is the difference between cube and groupBy for operating on DataFrames?

Question is pretty much in the title. I can't find any detailed documentation regarding the differences.

I do notice a difference because when interchanging cube and groupBy function calls, I get different results. I noticed that for the result using 'cube', I got a lot of weird null values on the expressions I often grouped by.

any sample MySQL databases I can download?

I'm doing some inter-database operational research e.g. synchronizing Oracle, MySQL, etc. Are there any nice MySQL databases that I can download, so that I can test some importing on real-world cases? I'm thinking of some open project that might have a weekly data dump available for download. Of course, anything similar for Oracle, SQL Server, etc is welcome as well.

SQL to detect adjacent duplicate rows (duplicates indicated by values in subset of columns)?

I'm trying to hunt down a potential bug in my application, and I'd like to see if there are duplicate events recorded for a user, which would be evidenced by duplicate data in two columns, user and value whereas the other columns could have slightly different meta data. Is there a way to identify such duplicates in a single SQL query?

lundi 25 juillet 2016

What will happen if we failed when writing the redo log?

I am learning about the implementation of database system, and it says that we write redo log before writing data when insert some item.When we failed to write the data, we can redo it from the redo log.But what if we failed when writing the redo log?Does is means that we can never recover the operation?

How to set offline a User in the DB when it closes the browser?

i have a logout function that sets the User offline in my DB (mysql), but if it just closes the browser, in my DB the User is still online despite it's not , How can i manage this? How can i set the User Offline without press the logout botton? Cheers in advance !

Ps: Yes, i'm using SESSION

Oracle - not single group func

I have table :

table blah:  
| name | nmb |
+------+-----+
| andy | 10  |
| alice|  5  |
| carol|  9  |

select name,MAX(nmb) from blah;

Not a single-group group function,
How to get output like :

| name | nmb |
+------+-----+
| andy | 10  |

Could anyone guide in the right direction?

Non-Uniform List of items TractSQL, how can create a table that handles this data?

To keep it simple I have Users and Skills. Skills could be like being able to speak Spanish or play football. It would not make sense for me to list all of the Skills possible. How can I address this issue?

Ex:

UID  Name  Skill 
  1  Tom   Football  Soccer  Baseball   Math
  2  Bob   Spanish   Band    

SQL:How return record by look up max assign column?

data soure:

id  data1   data2
1   1       4
2   1       5
3   2       6
4   2       7

I need find data2 max and same data1. I hope return:

data1   id  data2
1       2   5
2       4   7

I try to: select data1, id, max(data2) from table1 group by data1, id. But it false.

Is there another way to do this?

How to delete data from listview and sqlite?

I followed the tutorial https://tausiq.wordpress.com/2012/08/22/android-list-view-from-database-with-cursor-adapter/ but I cannot seem to figure out how to delete an entry , only add more to the listview and sql database.I do not fully understand this , can someone please help! Been trying different solutions in vain for 3 days now .

Using a named count() function in sql where section

Is it possible to us a named count function (I.E

SELECT n.name, **count(c.name) as freq** FROM names as n, names as c 
WHERE freq < 1 AND gender = 'f' order by rand() ) 

in the where column of a query, or would i have to do this another way?

SQL output display

Morning all, I'm trying to change the design of the output of my results For example Select a, b From table1 Where a like '500%' Output will result A b 500 user1 500 user 2 2500 userx 2500 usery I want to display it as A b 500 user1, user2 2500 users, usery Apologies if this is confusing, using my phone to type this. Thanks in advance.

How to query from a stored procedure in SQL Server?

Let say I have a simple Stored Procedure:

ALTER PROCEDURE [dbo].[myProc]
AS
BEGIN
   SELECT * FROM myTable
END

How can I do a WHERE statement in Microsoft SQL Server Management Studio to the stored procedure? Something like that:

SELECT * FROM myProc WHERE x = 'a'; -- But that doesn't work...

Can I count a certain scenario in SQL server?

I have a table looks like this

ID | I  | II | III | IV | V  |
1  | 1  | 0  | NULL|NULL|NULL|
2  |NULL|NULL|NULL | 0  |  1 |
3  | 1  |  0 |  0  |NULL|NULL|
4  |NULL|NULL|NULL |NULL| 1  |
.    .     .    .    .    .
.    .     .    .    .    .  
.    .     .    .    .    .

I am using SQL Server 2014. I am looking to count the number of ID that has the scenario like #1 and #3. Is there a query that can do that? Thanks!

Mysql Alias of alias

I'm trying to run this sample query :
SELECT * FROM (SELECT * FROM orders WHERE id > 2) AS o1 JOIN o1 AS o2 ON o1.id = o2.id;

but this error occur:

Error Code: 1146 Table 'pnu.o1' doesn't exist

how should i join the sub query with itself?

Laravel 4 - Select rows where count of rows in joined table greater than 0

I need to grab rows of users where rows of items exist. Here is my code so far: $users = DB::table('users') ->join('orders', 'orders.user_id', '=', 'users.id') ->join('items', 'items.user_id', '=', 'users.id'); How do I add a where condition that will only select users that have at least one item?

Suitable Driver Not Found?

Under which circumstances the following: Class c = super.findClass("com.mysql.jdbc.Driver"); java.sql.DriverManager.registerDriver((Driver) c.newInstance()); c.newInstance(); java.sql.DriverManager.getDriver("com.mysql.jdbc.Driver")<- This is crashing AFTER CREATING instance and using registerDriver(...). Can throw Driver not suitable exception? Server is up and running I am using 5.7.13, 1.8 JVM, and OS X 10.11.4. Thanks a lot!

FIX MYSQL General error: 1366 Incorrect integer value

The Error Code:

Exception information:

Date: Jun 16, 2016 20:21PM

Message: SQLSTATE[HY000]: General error: 1366 Incorrect integer value: '' for column 'id' at row 1

Code: HY000

My script has worked on MYSQL Version 5.5 but it is not working now on the MYSQL version 5.6.

Who can fix this error ?!

logging MySQL interactive queries

I have several people doing some database queries directly into some systems.

I would like to log to syslog all the queries done interactively/by hand, or failing that, all the queries done by using the mysql binary client.

I am using Debian Jessie, and Oracle MySQL 5.6.31

How could I achieve that?

Select values from two tables using “WHERE NOT IN” and DISTINCT in LINQ in Linq to Sql

I have two table like Customer and VisitDetail and i need to convert below SQL Query into Linq to Sql

select *
from Customer
where id not in (select distinct CustomerId
                 from visitdetail
                 where VisitDate='2016-06-13' and SalesRepAccId=1 and
                       RouteId=10
                ) and
      RouteId = 10 and Active=1 and SalesRepAccId=1

unable to insert the image in MySQL

I'm trying to insert the image in MySQL whenever i tried to add the image it showed null value. Pls help me to add the image. I've give the correct path but still error has occurred

create table image3(id int, image longblob not null);

insert into image3(id,image)values(571185, load_file('D:Images3.jpg'));

Remove multiple time intervals in mysql

I'm using the command below to remove time intervals like time between 9:25 am and 9:35 am but its not working.

WHERE TIMEONLY NOT IN ((TIMEONLY BETWEEN '09:25:00' AND '09:35:00') OR (TIMEONLY BETWEEN '11:55:00' AND '12:05:00') OR (TIMEONLY BETWEEN '15:10:00' AND '15:20:00'))

Any suggestions! I highly appreciate your help.

Rishabh

How to create a multivalued attribute on SQL

There is a way to create a multivalued attribute in SQL command?

enter image description here

There is a code:

CREATE TABLE fornecedor (
    Id INTEGER,
    Nome VARCHAR(30),
    Morada   ????????????????
    Email VARCHAR(20)
)

SQL Check if an update doesn't go below a certain level

I have a stock table (MySQL) which has item and quantity as the two fields.

When an update is performed for example:

UPDATE stock SET Quantity = (Quantity - ?) WHERE ItemName = ?

How can I perform a check and then send an error message to deny the update if the Quantity - Value is < 0?

Why not all of my tables are shown after mysql migration?

I am migrating my mysql 5.5.20 databases from a machine to another. After installing mysql and dropping my tables into the data directory, they are not showing with show or mysqlshow. I have used this drop in method several times over the years but this time, on a Vista machine, but they are now not being read by mysql or phpmyadmin. Why?

Select all fields value where all fileds value like some String

can someone help, i need to get all values from fields where all fields values like %someString%. My table have 17 fields, i don't want write all fields in query. DB Mysql.

select * from Deputes_APPEAL where filePath, checkForPlagiarism, contentOfResolution, countOfPages, dateForCheck, incomeNumber, incomingDate, mainWorker, nameAndAddressOfApplicant, nameOfDepute, outDate, outNumber, result, secondaryWorkers, shortContentOfAppeal, statusOfWorking, themeOfAppeal, TypeOfDeputeAppeal, unitWhoDoResolution like %someString%

Using merge how can i use where statement?

i'm using this code:

SqlCommand cmd = new SqlCommand(@"
MERGE customermaster  AS target USING
      Tamio.dbo.memberform  AS source
      ON target.id  = source.id 
WHEN MATCHED THEN
    UPDATE SET target.name = source.name
WHEN NOT MATCHED THEN
        INSERT (id, name) VALUES (source.id, source.name)
", conn);
cmd.ExecuteNonQuery();

Example:How can i execute mycode where active=1.

Update in hibernate with single database query

Suppose I have an employee class which has 3 fields - empId, empName and empAddress.

I want to update only address of employee with empId say 1. If I use session.update(emp), it will set empName as null, of course I don't want that.

Is there any way to achieve this in a single database query without using hql.

dimanche 24 juillet 2016

Importing SQL database Invalid default value for datetime

I am moving a database from one MySQL server to another, however when importing one table I end up with the error: 1067 - Invalid default value for 'date' the table SQL: CREATE TABLE IF NOT EXISTS `log` ( `id` int(11) NOT NULL, `date` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP, `url` text NOT NULL ) ENGINE=InnoDB AUTO_INCREMENT=165 DEFAULT CHARSET=utf8 Importing to MySQL version 5.5.47 from 5.6.21

Select count of unique values that might appear in different columns

I am trying to get a count on values that might appear in 3 different columns but only require the count of unique values. Microsoft SQL. Eg. value X might appear in column A, B, or C or all 3 but need to make sure I only get a unique count of value X no matter what columns it comes under.

Thanks!

Installing MySQL on Ubuntu 16.04 (unmet dependencies)

I have a fresh install of Ubuntu 16.04 and setting up a Lampp server. PHP7 and other elements installed fine but MySQL wont. Below is a screenshot of the terminal after running sudo apt-get install mysql-server:

Result

#1055 - Expression of SELECT list is not in GROUP BY clause and contains nonaggregated column this is incompatible with sql_mode=only_full_group_by

the is my Query : select libelle,credit_initial,disponible_v,sum(montant) as montant FROM fiche,annee,type where type.id_type=annee.id_type and annee.id_annee=fiche.id_annee and annee = year(current_timestamp) GROUP BY libelle order by libelle asc Mysql 5.7.9 runs the query without any problem but mysql 5.7.12 display the error above Could you please help me with that

how to execute .sql file in linux. Beginner

I am a beginner. I just created the most basic sql file but i don't know how to execute it or what to do with it? I'm using linux that too for the first time. Also what is the database name of that file? I'm new to sql and linux both. help me how to do it with the help of command lines

How to Query Equal/Non-Equal Values Across Multiple Columns in a Table

I am fairly new to SQL and I had a question about querying across multiple columns with equal/not equal values.
I need to pull results where values in

Column A = Column A AND Column B = Column B AND Column is NOT equal to Column C. 

Does anyone know if something like this is possible? Thanks.

Join Postgresql tables on json array columns

I have two tables in postgresql with json array columnstableA.B and tableB.B. How to join these tables on these json columns? i.e.

select tableA.id, tablA.A, tableB.id,tableA.B, tableB.name
from tableA, tableB 
where tableA.B = tableB.B 

--tableA--
id | A     | B                 
1  | 36464 | ["874746", "474657"] 
2  | 36465 | ["874748"] 
3  | 36466 | ["874736", "474654"] 

--tableB--
id | name  | B                 
1  | john  | ["8740246", "2474657"] 
2  | mary  | ["874748","874736"] 
3  | clara | ["874736", "474654"] 

How to insert two columns of two tables into one column of other table

Hi I am having trouble joining 3 tables

table1(id1,name_1)

Table2(id2,top,name_2,fk_id1)

table3(id3,top,name_3,fk_id1)

and as a result i want o have:

tableResult(id1,name_1,top,name_2,name_3)

ps: top contain data from table2.top and table3.top

Does quoting of identifiers improve security?

I know that in MySQL we can quote identifiers with back tick symbol, whereas in Oracle (and other RDBMS that follow standard) we can use double quotes around table names and field names. I wonder whether it somehow improves security and should we use this technique in real world applications in parallel with traditional methods like preparation of sql statements?

SQL - generate alphanumeric string with specific format

I need to find out how to generate an alphanumeric string that follows the format like in the answer for this question which I'm currently using, except it has to be in the following format:

Vowel + consonant + vowel + consonant + 4-digit number

For example ABAB1111 or IJUZ9236.

Thanks for any suggestion.

Mysql query of 200000 rows and performace

i have build a custom cms on php/mysql and bootstrap. Speed is pretty decent under 0.2s load time. But i want to implement a feature to get user ip and see if it listed on the database which will have 200000 ips in rows and im afraid of speed drop. Any suggestion for me please, or should i do it via json or? Thank you

Check constraint vs proper lookup table

I need to use sets in standard SQL. I need describe column type like selection from set of something (Example Color=[Red, Green, Blue] ). I can use check constrain or create lookup table with tree records - Red,Green,Blue. What are pluses and minuses of each method. I need to make this solution universal and use in much as possible SQL servers.

Is there a Max function in SQL Server that takes two values like Math.Max in .NET?

I want to write a query like this:

SELECT o.OrderId, MAX(o.NegotiatedPrice, o.SuggestedPrice)
FROM Order o

But this isn't how the MAX function works, right? It is an aggregate function so it expects a single parameter and then returns the MAX of all rows.

Does anyone know how to do it my way?

Mysql Delete Query from tow table

Hello I Have write Delete Query

delete installments . InstallmentID , Installment_part . InstallmentID  , Installment_part.Parts_ID ,Installment_part.*  FROM installments
    INNER JOIN
Installment_part ON installments.InstallmentID = Installment_part.InstallmentID 
WHERE
(((installments.InstallmentID) = 7)
AND ((Installment_part.InstallmentID) = 7));

It Give me this Error Unknown Table InstallmentID i have change it to Select Statement and it show me what i want to Delete

Phone number pattern to clean up

I have phone number field to clean up and trying to find the junk number which are in this format patterns of numbers: like 000000 ,111111,222222,3333333,4444444,.... Phone ---------------- (444)333-7777 555.666.6666 333.555-7777 222-222-2222 1111111111 5104554535 (555)(353)(5343) Phone(output i want to see is) 222-222-2222 1111111111 and second question i want to know the count of the records has special characters.from the above phone field i want to get 5 as count. Your help is appreciated.

Django raw SQL with WHERE

What is wrong with this syntax,

postModel = list(PostModel.objects.raw(
'SELECT * 
WHERE author = "art", max(pub_date), count(topic_id) 
AS freq, count(DISTINCT author) 
AS contributors 
FROM crudapp_postmodel 
GROUP BY topic_id 
ORDER BY pub_date DESC'
))

All worked fine before I put in WHERE author = "art"

OperationalError: near ",": syntax error

Thanks

MySql: any way to: UPDATE $tableName SET value=LEAST(value+$change, maxValue)

As the question-title says i am searching for a way to achieve this in only one sql-call:

UPDATE accountEnergy SET value=LEAST(value+$energyChange, maxValue)

My solution with two calls:

mysqli_query($db, "UPDATE accountEnergy SET value=value+$energyChange WHERE accountId=$accountId");
mysqli_query($db, "UPDATE accountEnergy SET value=maxValue WHERE accountId=$accountId AND value>maxValue");

Put N Unicode before variable in sql server?

We usually use N for unicode string literals like that:

Select * 
From Customer 
Where Name = N'កខគ' --Unicode

Now I want to change to be like that:

Declare @a varchar(Max)

Select * 
From Customer 
Where Name = N''+@a

At the second SQL statement it doesn't work at all. Any ideas? Thank you in advance.

Sub Query SQL to display grouping, count, put it on up

I have one table on database

No  |  Nomor ID  | Name   | chairman (if as chairman id=1, if not = 0)
1   | 1234       | Brian  | 1
2   | 1234       | Dol    | 0
3   | 5555       | Mon    | 0
4   | 5555       | Tue    | 1
5   | 5555       | Nom    | 0

I want to, display it with

Nomor ID |  Name | Chairman | count 
1234     | Brian |     1    |  2
5555     | Tue   |     1    |  3

I was try any possibilities.. but can't , to display "name" put on it like that

May you know solution

how to upload and retrieve doc/pdf in mysql

I'm writing an application that allow user to upload word document onto the server. I am thinking on how what the best practice for storing uploaded document is. 1) Store the document as a file in the file system and create a record in a table with the exact path to that document. 2) Store the document itself in a table using a "doc" or "binary data" data type of the database server.

Odbc & Sql connection in one query

I wanna select some records from the informix database via Odbc connection and insert them to a Sql database table.

INSERT INTO SAS.dbo.disconnectiontemp 
        (meterno) 
SELECT DISTINCT met_number                 
FROM   Bills.dbadmin.MeterData 

I've searched regrading that, but they didn't solve my issue. Is it possible to have both connections at one place?
Any help or suggestions would be appreciated. Thanks

Can we have one database for different programming languages, what would be the difficulty to club all solutions in a single business suite [on hold]

I am in chaos situation in deciding Programming language with database for different solutions. if i want to include all of application packages as a single solution then what would be the problem. Can any one suggest the best resolution. Example : Application 1 : Programming Language is php and database is MySQL. Application 2 : Programming Language is java and database is MySQL. Application 3 : Programming Language is dot net and database is MySQL.

The requested URL /embed--728x410.html was not found on this server

i have some problems with this website to see some films

http://putlocker.is/watch-the-mummy-tomb-of-the-dragon-emperor-online-free-putlocker.html

when i try to see this appear:

The requested URL /embed--728x410.html was not found on this server.

Apache/2.2.15 (CentOS) Server at thevideos.tv Port 80

how i can to fix it please.

Wy decimal numbers are not stored as expected in mysql

I'm trying to save numbers in decimal data type filed formated (10,4), but it's not stored as expected ie. 13850 changed to 13.0000 any help. this is my code:

$c_price = $unit_price*$rate;
  $expense->c_price = number_format($c_price, 4);
  $expense->c_total = number_format($quantity*$c_price, 4);

Here c_price and c_total values are changed.

samedi 23 juillet 2016

SQL Server: Msg 156, Level 15, State 1, Line 2 :Incorrect syntax near the keyword 'on'

I'm new to using SQL Server and I face a problem which appear this error

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'on'

As you can view in this screenshot

enter image description here

Thanks

Use REFERENCES in Vertical Fragmentation table in Oracle

First create the following tables in two different databases

Fragment1:
Employee(EID number(4)PRIMARY KEY, Name varchar2(20),Address varchar2(50));

Fragment2:
Employee(EID number(4),Dep_Id number(4),Mgr_Id REFERENCES Employee(EID),Salary number(6));

and then Create a trigger to insert data into appropriate table.

I am not able to use REFERENCE Employee(EID) [of Fragment 1] in Mgr_Id

Please Help

How to get month value using week value sql server

I want to get month value using week no. I have week numbers stored in a table with year value.

enter image description here

How to query database to get month value using that week value.

I am using SQL

How to get a query to count the total rows?

How to get a query to count the total rows? My query:

enter image description here

enter image description here

Incremental table index

In all SQL tables I'm using incremental index with name id. I'm not sure I'm right since I have heard that some SQL servers increment it's records as default. I'm right? How to get these default increment fields values then in different SQL servers?

Another question in case I use my own id - what data type I should use for this field? Currently I'm using int type.

How to stop MySql process running permanently?

I want to stop MySql running on my local machine ,because I have it conflicted with mySql in docker container.

I get this ,(not sure if it's a "real" mysql process )

ps auxwww |grep mysql
root     13277  0.0  0.0  13192  2168 pts/3    S+   22:02   0:00 grep --colour=auto mysql

Have tried :

service mysql stop

echo "manual" >> /etc/init/mysql.override

sql server query about unix time

i have a 4-column table with ships' signal entries. 1st column is unix time with a 3-month rows entry. 2nd is the name of a ship. 3rd is the longitude. 4th is the latitude. There are many entries of the same ship with different time. i want a sql server query, to find the table rows which a ship , doesn't have an entry for more than 10 minutes and less than 5 hours.

Sort A to Z Tables in sql

how can i sort A to Z tables with Tables name in SQL SERVER? for example :

  • dbo.customers
  • dbo.zone
  • dbo.jobs
  • dbo.account

sorting like:

  • dbo.account
  • dbo.customers
  • dbo.jobs
  • dbo.zone

Priority any button in menu bar or something then query for sorting, Thanks

Regarding multiple image upload using PHP

I am newbie in PHP and i am developing a component where user can upload total 5 images which will be stored in database. Right now my component is able to multiple images but i won't set the limit(only 5 images can be uploaded). Also i want user can see all 5 images and can select any one to use as profile image. I am using code from http://www.codexworld.com/drag-and-drop-file-upload-using-dropzone-php/ for image upload.

SQL Joining tables to get other tables data

Please have a look at the following fiddle: http://sqlfiddle.com/#!9/ebddb/1/0 Here you see it's returning doubles (id, notchid and number should be unique). My Question: Why does it return doubles and how to prevent it? P.s. I found out that when there at least 6 records in notchtype, there are suddenly no duplicates anymore. And the null values should indeed be null. They have other values then an integer corresponding with notchtype.

Varchar and varbinary error hashbyte

I need to write the following in dynamic sql

select HASHBYTES('SHA2_256',CONVERT(VARCHAR(256),'String'))

set @sqlstr = 'select ' + HASHBYTES('''SHA2_256''',(CONVERT(VARCHAR 
(256),'String')))   

But I got error the following error message:

Msg 402, Level 16, State 1, Line 6 The data types varchar and varbinary are incompatible in the add operator.

How will I solve it?

MySQL should I ever use USE INDEX and when?

I came across suggestion that I should never use "USE INDEX" to tell MySQL which index to use. An expert said I should leave the decision to optimizer. That probably means I should just create indexes on columns that are most needed and not worry about it anymore. It would be really good if I can do that and rely on optimizer.

What do you think about that? Any pitfalls?

Efficient way to dedupe Hive table?

I'm working with a data pipeline similar to Airflow and want to have a daily task that checks if a new partition has landed in a table and then create a new table with all duplicate records removed.

The dataset is quite large, so I'm struggling to think of an efficient HiveQL query to dedupe it with. Simply using a group by over all the columns is certainly too expensive.

Oracle query to find the top 2 item per group

I want to right a sql query to find the top 2 item per group in oracle.
The table contains:

P_id Price GroupX
1     10    a 
2     5     a
3     5     a
4     4     b
5     8     b
6     6     b

Output should be:

P_id Price  GroupX
1     10      a
2     5       a
5     8       b
6     6       b

What I have tried is:

Select * from table
group by GroupX
order by price desc
limit 2

Calculating the Lines of Code Estimate for a PHP, MySQL, HTML web app from Function Points

We need to convert our Function Point estimation to a Lines of Code estimation for our web application, which uses HTML5, PHP, MySQL and CSS3. The total number of function points we ended up with was 1727.24. What would be the best approach? All we can find are ways to convert client side software (eg C++, Perl programs etc) function point estimations to LOC applications. Even a link to a helpful website would be greatly appreciated.

SQL query - Finding the max value of an attribute without a subquery

Consider the relation Book with the following simple schema

Book(title, pages)

I want to find the title(s) of the book(s) with the highest number of pages, but without using a subquery.

Is this possible?

EDIT: This is not for a particular DBMS. I'm studying from a book (which uses the SQL-99 Standard) and this is a part from an exercise.

In SSAS cube related Query

i am a junior software developer . I am stuck at one point that my client want to add 8000 roles in its cube with filter condition on branch name.

For example .

  1. Mumbai sales person can only access Mumbai data .

  2. Gujarat sales person can access only Gujarat data.

like wise 8000 city are there. IS there any way to solve this issue ?

Test specification in testlink to be modified with 'Notes' custom field adding to filter criteria

You can see 'Notes' text area.I added it. Now I need this as a filter criteria.Need to add filter criteria called 'Notes' . In attached screenshot I added the text area for Notes section. Now I need to search with applying this search criteria. Which Testlink files to be modified?

mysql select max & group by

http://i64.tinypic.com/wb7y2b.png that's my table

how do that? i try that and it gives only 1 max exp1 result...

   "SELECT * FROM table1
WHERE (product_id=$id AND group=1) OR
 (product_id=$id AND group=1) OR
 (product_id=$id AND group=4) OR
 (product_id=$id AND group=7)
GROUP BY group"

New field with the date of the subsequent row

ID      Name           Request Date
296459  Waiting        2016-06-04 22:53:46.000
296459  ED-22          2016-06-04 23:01:30.650
296459  CCS-CC28-A     2016-06-05 01:16:00.000
296459  4N-N450-A      2016-06-14 06:33:41.530

I would like to create a new row called End Date which would contain the Request Date from the next row.

ID        Name           Request Date             End Date
296459  Waiting        2016-06-04 22:53:46.000  2016-06-04 23:01:30.650
296459  ED-22          2016-06-04 23:01:30.650  2016-06-05 01:16:00.000
296459  CCS-CC28-A     2016-06-05 01:16:00.000  2016-06-14 06:33:41.530
296459  4N-N450-A      2016-06-14 06:33:41.530  GETDATE()

Meaning of "Select tables optimized away" in MySQL Explain plan

What is the meaning of Select tables optimized away in MySQL Explain plan?

explain select count(comment_count) from wp_posts;

+----+-------------+---------------------------+-----------------------------+
| id | select_type | table,type,possible_keys, | Extra                       |
|    |             | key,key_len,ref,rows      |                             |
+----+-------------+---------------------------+-----------------------------+
| 1  | SIMPLE      | all NULLs                 | Select tables optimized away| 
+----+-------------+---------------------------+-----------------------------+
1 row in set (0.00 sec)

Note: explain plan output edited for legibility.

Mysql get values from all rows but in one record by comma separated

Below is my table

-----------------------------------
|id|     |Zone|    |State         |
--------------------------
|1|     |Zone1|    | State1,State2|

|2|     |Zone2|    | State3,State4|

|3|     |Zone3|    | State5|

I try with group concatenate it shows 3 different records, I want in one record all concatenated by comma like

State1, State2, State3, State4, State5

I try with this query

select group_concat(state separator ',') as state from zone group by title

Updating of data SQL [duplicate]

This question already has an answer here:

I have been parsing data, I receive data and compare them with the data in my database. Tell what command only non-existing data can be inserted? And if come data that already exists in the database, nothing happens.

How to write a SQL script to read contents of a file

I have a SQL script and a ".csv" file. I want the SQL script to read the data from the ".csv" file instead of manually entering the data in the script. Is it possible?

....
.....
......
and SP_F.trade_id = SP_R.trade_id 
and SP_R.iSINCode IN (here is where I can manually enter the data)

ps: I am new to SQL and I am still learning.

vendredi 22 juillet 2016

Need to fetch record for each month in MYSQL

I need help to fetch record from the database with some condition as I explain below :- I need to check the student availability for each month between selected startDate and end Date. Table Structure :- Table data :- Example :- Here you can take capacity of classroom as 20 students for example. I want to check the seat availablity from 02/2016 to 04/2017. Output will be : 02/2016 - 20 03/2016 - 19 04/2016 - 18 05/2016 - 15 06/2016 - 20 . . . 02/2017 - 14 03/2017 - 20 04/2017 - 18 thanks in advance for help.

Mysql- how to select last 100 recodes from a table

Please can anyone help me with this php/mysql code

$view->pch = $db->Query("SELECT from_unixtime(`pauc_date`), `pauc_ad_id`, `pauc_domain`, `pauc_word`, `pauc_referer`, `pauc_ip`, `pauc_country`
                         FROM publisher_ad_units_clicks 
                         WHERE pauc_user_id=?", "i", $USER_ID);

i need to change this query to get only last 100 rows. because table has thousands of rows and slow down the page loading.

Get query from an external DB in Wordpress

Actually I have a php website in my hosting. Now I am personalizing a Wordpress theme to replace it. It's all ok for now, but the old website has a built in function to connect to another database with a token. This connection is only to get some data.

Can you tell me how to implement this in my new wordpress theme?
Did a wordpress plugin exists for this?

Thanks

SQL: Conditional Insert/Update

Hi I am working with a table like the one below in SAP HANA:

Outcome  Value  Rating
Yes       0      null
Yes       20     null
No       -16     null

I need to populate the Rating column conditionally so that if:

Value > 15; Rating = 'High"
-15 <= Value <= 15; Rating = 'Medium" 
Value < -15; Rating = 'Low"

Is there anyway I can do this using an INSERT or UPDATE statement?

How to compare two dates to find time difference in SQL Server 2005, date manipulation

I have two columns:

job_start                         job_end
2011-11-02 12:20:37.247           2011-11-02 13:35:14.613

How would it be possible using T-SQL to find the raw amount of time that has passed between when the job started and when the job ended?

I tried this:

select    (job_end - job_start) from tableA

but ended up with this:

1900-01-01 01:14:37.367

GETDATE scalar variable

I'm retrieving a must declare scalar variable error for @StartFixtureDay but not sure what I need to do or see the problem with my code:

CREATE PROCEDURE [dbo].[Date_Insert]

AS
SET NOCOUNT ON
BEGIN

DECLARE @StartFixtureDay DATE
SET @StartFixtureDay = CAST(GETDATE() AS DATE)

    ;WITH League_Dates AS (
...
 SELECT rn,
           week_number,
           DATEADD(day, week_number - 1, @StartFixtureDay) AS WeekNumber,
...

...

EXEC [dbo].[Date_Insert] @StartFixtureDay

How would I use ON DUPLICATE KEY UPDATE in my CodeIgniter model?

I have a CodeIgniter/PHP Model and I want to insert some data into the database.

However, I have this set in my 'raw' SQL query:

ON DUPLICATE KEY UPDATE duplicate=duplicate+1

I am using CodeIgniter and am converting all my previous in-controller SQL queries to ActiveRecord. Is there any way to do this from within the ActiveRecord-based model?

Thanks!

Jack

Is it good practice to have individual database for testing an application for each developer

My company has decided that each developer should have its own database locally for testing the Asp.net web application. I am against the decision as I think there should be a centralised test database for testing. But the developers put an argument that if they test the same table and other developers delete the records while I add the records at the same time it will create incorrect result. So what you guys think.

What is wrong with the following query giving me SQL exception? [on hold]

the following query is giving me Exception
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'equipcompany.NEquipments=equipcompany.NEquipments+100 WHERE equipments.EId=25 An' at line 1

 String query="UPDATE equipments, equipcompany SET equipments.Econdition=? 
equipcompany.NEquipments=equipcompany.NEquipments+? WHERE equipments.EId=? And 
 equipcompany.Eid=?;";

SQL Server : get max of the column2 and column3 value must be 1

I have an output of some part of my stored proedure like this:

col1      col2  col3 col4
--------------------------
2016-05-05  1    2      2
2016-05-05  1    3     32
2016-05-12  2    1     11
2016-05-12  3    1     31

Now I need to get result based on this condition

col2 = 1 and col3 = max or col3 = 1 
and col2 = max

The final result should be

col1      col2  col3 col4
-------------------------
2016-05-05  1    3     32
2016-05-12  3    1     31

ubuntu 14.04 no /etc/mysql folder after installing

I am trying to install mysql and later phpmyadmin on a ubuntu 14.04 server after initial install.

So far I have configured Apache.

there is no mysql folder inside /etc/

I used the command sudo apt-get install mysql-server to install mysql

When I do this I have no prompt for a password and the mysql folder is still not created inside /etc/ but it says it installed anyway.

How to fill in the dates in between a min and a max date from a column

I hope I can explain this well enough. I'm trying to create a table with a date field that uses a date column from another table to grab the min and max dates from that column, and fills in all the dates in between. So if the min and max dates were 1/1/2016 and 6/1/2016 then I would want the table to list every date in between those dates. I am using SQL Server Management Studio 2014. Thanks for your help.

output with diacritics in Full-Text search

I have these in Table_1:

بود

بُود

How can I see بود and بُود in the output?

EDIT: SELECT * FROM Table_1 WHERE contains(*, '"بُود"', LANGUAGE 1025);

CREATE UNIQUE INDEX ui_ukJobCand ON Table_1(Family);
CREATE FULLTEXT CATALOG ft WITH ACCENT_SENSITIVITY=OFF AS DEFAULT;
CREATE FULLTEXT INDEX ON Table_1(Family LANGUAGE 1025)
KEY INDEX ui_ukJobCand WITH CHANGE_TRACKING AUTO, STOPLIST = SYSTEM;

What is wrong with this small query? SQL errors

I have this Query:

INSERT INTO abilities_usage (id, name, usage) 
      VALUES 
("5467", "naga_siren_mirror_image", "1") 
ON DUPLICATE KEY UPDATE id='5467';

SQL response:

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'usage) VALUES ("5467", "naga_siren_mirror_image", "1") ON DUPLICATE KEY UPDATE i' at line 1

Why?

How to increment a field in MySql using "ON DUPLICATE KEY UPDATE" when inserting multiple rows?

How to increment a field in MySql using "ON DUPLICATE KEY UPDATE" when inserting multiple rows?

For one row:

INSERT INTO table 
  (a, counter_elem) 
VALUES 
  (1, 1)
ON DUPLICATE KEY UPDATE counter_elem = counter_elem+1;

For multiple rows:

INSERT INTO table 
  (a, counter_elem) 
VALUES 
  (1, 1),
  (2, 1)
ON DUPLICATE KEY UPDATE counter_elem = ?;

This doesn't work:

counter_elem = VALUES(counter_elem)+1

How to remove a prefix name from every table name in a mysql database

I have a joomla mysql database with a table name prefix of "jos_" on all of my table names. But I would like to remove it from all of my tables. I understand how to rename each table, one at a time, but I have 600 tables. Is there an easy to run a sql query to do this.

If someone has a solution, could you please post the exact sql query I can use?

How to add a "search bar " bundle or funtion in a Symfony 2 app

I wanna add a search bar composant to filter my results of searching. Actually I have just a function which gives me all the data from DB.

public function indexAction() {
    $em = $this->getDoctrine()->getManager();

    $entities = $em->getRepository('MaisonMaisonBundle:Maison')->findAll();

    return array(
        'entities' => $entities,
    );
}

I want to just add an SQL request which gives me a filtered result, even a search bar bundle.

When using mysql to check for a value, it doesn't return anything? [on hold]

So, I have a mysql table named: "cake_users" Here's what it looks like and how it's structured 1 name1 4588yrue38r authkey114 2 name2 4o857398563 authkey124 3 name3 93784ee8753 authkey115 4 name4 12345678910 authkey164 id, name, hwid, authkey I'm trying to run this query: $hwidid = "'12345678910'"; $cakequery = mysql_query("SELECT * FROM cake_users WHERE hwid = {$hwidid}"); if(mysql_num_rows($cakequery) == 0) { echo 'FALSE'; } else { echo 'TRUE'; } But it always echo's false even though 12345678910 is in the database? What am I doing wrong?

Should I use addslashes function when I using PDO?

I heard that PDO defends Injection Attack automatically. So, I can make a query without ' mark. Then, should I use addslashes function when I using PDO? I means... <?php $s = $d->prepare("SELECT * FROM `table` WHERE `no`=:n"); $s->bindParam(":n", $data); $data = $_GET["param"]; $s->execute(); ?> or <?php $s = $d->prepare("SELECT * FROM `table` WHERE `no`=:n"); $s->bindParam(":n", $data); $data = addslashes($_GET["param"]); $s->execute(); ?>

SQL case when with 2 different types of output

Table

c1     c2  c3
'a1'   1   'hi'
'b1'   2   'hee'
'c1'   3   null

When I do

select case when c3 is null then c2 else c1 end from Table

I get a "Conversion failed when converting" error.

I know that case when can only return 1 type, but is there a way to convert varchar to int/tinyint? If not, is there another way?

Note Code : 1973 Can't create user 'user'@'localhost'; it already exists, Mysql

once I created a user named 'dscl' and deleted afer few days. Now when I am trying to create a user named 'dscl'it is showing me an error message as below.

Note Code : 1973 Can't create user 'dscl'@'localhost'; it already exists

I executed a query (select * from mysql.user;) to check user list and it is not showing any user named 'dscl'.

What could be the cause?

Ruby on Rails / ActiveRecord and Table Partitions

I've read the documentation and been able to find anything to assist me so far. I've also read a large number of blog articles, but nothing seems to answer my question directly:

Is it possible to manage table partitions in an InnoDB table from with ActiveRecord? I'd really prefer to keep things very clean and I'm trying to avoid writing external scripts to try to automate the creation/deletion of partitions over time.

would mysql cluster help my situation?

I am dealing with several gigabytes of WAF logs. What I mainly do is searching for some pattern using "select * from tbl where condition1 and condition 2 and so on" The problem is the columns are not indexed. It takes 5~10 minutes to just one simple select query with some conditions. I am thinking about adopting mysql cluster for better performance and stability. Would it help my situation? or is there any better way to do it? Thanks in advance :-)

PHPMyAdmin search not finding text? [on hold]

I want to search and replace our old domain, example.net, to example.com in our MySQL database.

When I try to search in the database using PHPMyAdmin, It returns 0 matching records, but when I downloaded the database to my local computer and opened it using Notepad++, I found more than 1000 matches searching for the old domain (example.net).

How is it possible?

jeudi 21 juillet 2016

Update SQL table from Excel without creating a temporary table

I have a table in MS SQL Server 2012 which looks something like what is shown below but with several hundred records id | adminnumber | 1 006 2 012 3 239 4 546 5 123 6 637 I have an excel sheet which contains proposed updates for these several hundred records of the adminnumber field so the sheet contains something like adminnumber original | adminnumber change 006 673 012 134 239 435 546 783 123 347 637 903 Is it possible to write a script to update the adminnumbers from adminnumber original to adminnumber change and is it possible to do so without creating a temporary table?

Data is missing from master to slave. Slave is working fine

what is the reason if some tables data is missing in slave but this data is available on master server when we check the slave is working fine.

  1. May be its there is problem in Mysql_bin.log because the slave is read the data statement from there may be there is problem with master its not writing in Mysql_bin.log file.

What you says guys. Help me out on this.

How to dynamically show new notifications using?

thanks for giving your time .

I have a webpage which fetch "Notifications " created by admin to users from a MYSQL database using PHP script. Now i want to that if Admin create a new notification It should be Dynamically added to user page.

just like Facebook , when a user is logged in and his friend post something , at that instant i can see a Notification of new post Without reloading the page.

How to Select Count for every user within a table

I have a Table named "Calls". The table's columns are organized as

CallCounter, AssignedEmpID, CompletedByEmpID
1            200            200
2            200            200
3            201            200
4            200            200
5            201            201
6            201            200
7            200            200
8            200            200
9            200            201
10           201            201
...

How do I create a Select SQL query that will return the following data. Ideally I would like to complete the entire SQL query in 1 query.

Employee    # Calls Assigned    # Calls Completed
200         6                   7
201         4                   3

I have tried the following queries

SELECT AssignedEmpID, COUNT(CallCounter) FROM CALLS
SELECT COUNT(*) FROM Calls

Oracle: Partition table by month

My solution(months in german):

PARTITION BY LIST ((to_char(GEBURTSDATUM, 'Month'))) 
(  
  PARTITION p1 VALUES('JANUAR'),  
  PARTITION p2 VALUES('Februar'), 
  PARTITION p3 VALUES('MÄRZ'),  
  PARTITION p4 VALUES('APRIL'), 
  PARTITION p5 VALUES('MAI'),  
  PARTITION p6 VALUES('JUNI'), 
  PARTITION p7 VALUES('JULI'), 
  PARTITION p8 VALUES('AUGUST'),
  PARTITION p9 VALUES('SEPTEMBER'),
  PARTITION p10 VALUES('OKTOBER'), 
  PARTITION p11 VALUES('NOVEMBER'),
  PARTITION p12 VALUES('DEZEMBER') 
);  

This doesn't work because of the to_char function.

replicate tables from mysql database to online hosting server having cpanel (5gbfree.com)

I am looking for a way to mirror or replicate a local MySQL database to an online hosting website which is 5gbfree.com. I saw the master slave replication but don't know how to use it with an online server. Can you help me please ?

I tried setting the online database as the slave but it didn't work.

problem

I don't know how to configure the online database as the slave.

Writing query results into a file

I've problem when I write the result of a query into a file.

string file = @"C:UsersjakubDesktopplik.pdk";
FileStream fs = new FileStream(file, FileMode.OpenOrCreate, FileAccess.ReadWrite);

string connection = "DSN=PervasiveData;Database=BAZA1";
string query1 = "SELECT skrot FROM KONTRAHENCI WHERE id = 32";

OdbcConnection MyConn = new OdbcConnection(connection);
OdbcCommand MyCommand = new OdbcCommand(query1, MyConn);

And now I must write to file my result of query.

How can I do this?

How to sort when using concat in group_concat mysql [duplicate]

This question already has an answer here:

Im in a situation where i need to sort date in concat within group_concat while my query is running fine

 SELECT 
    report.`Name`,
    GROUP_CONCAT(
      CONCAT(
        "[",
        DATE(report.Date),
        ',',
        report.ProductPrice,
        "]"
      ) 
    ) AS ProductPrice  
  FROM report
 GROUP BY report.Name ;

SQL with WITH clause too many values error

--This query is returning a "too many values" error. I'm not sure why?

   update myTable
            set var1= var2
            WHERE value1 IN (

             WITH X AS
            (
            select value1, value2, var1,var2, ROW_NUMBER()
            OVER
            (PARTITION BY value1 ORDER BY value1 desc) as rn
            from
              mytable WHERE var1 is null AND rownum>0 and rownum<=10 order by value1 asc
            )
            SELECT
            value1, value2, var2,var1
           FROM X WHERE rn=1  and var1 is null and rownum>0 and rownum<=10);

Using SQL code with excel power pivot

I'm using SQL code (which I do not know, I just tried to copy from a sample tutorial) to merge documents to use in Excel PowerPivot. I have an excel file called 2014, and another file called 2015. This was the syntax shown in the example to merge the two, but it keeps telling me columns not identified. How can I fix this?

SELECT ['2015$'].*  FROM ['2015$']
UNION ALL 
SELECT * FROM 'C:Alex2014.xlsx'.['2014$'];

How to use variable on looping in SQL Server

I have some varchar variables like this:

@var1='data a', 
@var2='data b',
@var3='data c', 
...,
@varn='data n'

I want to insert these variable on looping script.

DECLARE @counter INT
SET @counter = 1

WHILE(@counter <= n)
BEGIN
    UPDATE [table] 
    SET [header] 
    WHERE data = [@var1-n]

    SET @counter = @counter + 1
END
GO

How to make @var1 - @varn can use with loop on [@var1-n]?

Timestamp conversion to date, time and duration calculation

I have scheduled tasks table where I store scheduled task id, type, exec_time, end_time etc...

I get the exec/end time as timestamp.

For BI purposes I need to somehow calculate the duration (end_time - exec_time) and return it in hh:mm:ss.

The format of the exec/end_time is dd/mm/yy hh:mm:ss:miliseconds o'clock.

Please help me with this. Thanks in advance! Steve

Joining tables and displaying columns with different conditions

I have 2 tables: CTU contains columns 'course_id', 'user_id', and 'date' NU contains columns 'name' and 'id' user_id in table CTU has the same info as 'id' in table NU. I want my output to display the following: name | date where course_id = 1 | date where course_id = 2 I can get the first 2 columns to appear with a simple query, but I don't understand SQL JOIN's and subqueries very well so I'm having a hard time getting the last column to display.

how to update a resulting table from a query

i m trying to update a table which is a shorter version of my original table. What i have is the following:

UPDATE (SELECT * FROM bookings_tbl
where ACCOUNT LIKE 'RENTA%' AND PART_TYPE ='HARDWARE')
SET PART_TYPE= 'EQUIPO' WHERE PART_TYPE='HARDWARE';

don't know if it s possible, but i would like to have what is stated as HARDWARE in that small table saying EQUIPO. i m using micros SQL Server Mgmt Studio

Create users for PROFTPD with PHP

I am following the guide to use MySQL to create users in proFTPd. To encrypt passwords, the guide uses the following command:

/bin/echo "{md5}"`/bin/echo -n "password" | openssl dgst -binary -md5 | openssl enc -base64`

I wander how I would do this in PHP? I have googled this but I can't figure out how to implement this command in PHP. Is it just the MD5 hash of the base64 encoded form of the password?

Return zeros in empty query result

I have this query:

SELECT 
    --DGC.Name
    [GameChannel], 
    SUM([AdjustedGames] ) *100. / SUM(SUM([AdjustedGames])) OVER()  [Percentage]
FROM #GameChannelResults1 GC
--LEFT OUTER JOIN [WarehouseMgmt].[DimGameChannel] DGC ON DGC.Name = GC.[GameChannel]
GROUP BY [GameChannel]--DGC.Name

But when there is no match it returns empty result(nothing).I want to put somehow all values from [WarehouseMgmt].[DimGameChannel].Name as GameChannel and 0 for percentage if there is no match or result is empty. How i can do that?

SQL table doesn't appear on page

I'm having some problems with displaying my table on a html page. Here's the code:

        $resultaten = $conn->prepare("SELECT * FROM GastenBoek ORDER BY ID DESC");
    $resultaten->execute();
    while($rij = $resultaten->fetch(PDO::FETCH_ASSOC))
    {
        $ID = $row['ID']; //Hier zeg ik : haal ID uit Row.
        $Email = $row['Email'];
        $Bericht  = $row['Bericht'];
        $Tijd = $row['Tijd'];
        $Datum = $row['Datum'];
        echo $Email;
    }

I've tried using PDOStatement but that didn't solve it at all. Thanks in advance.

Java EE, purpose of an Object instance inside a contructor of another Class

I was watching the code of an advanced student and I saw something that I haven't seen in any tutorial. An object was instantiated inside the constructor of another class. Something like this:

public class Student {
    private String name;
    private int age;
    ...

    public Student() {
        Course course = new Course();
    }
}

The app uses a database that has Course and Student tables. What is the purpose of that? Does it have something to do with the foreign key?

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; gives an error

I have problem with mysql database. I can't import a database from my friend. I need some help.

SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
SET time_zone = "+00:00";

ERROR:

Unexpected beginning of statement. (near "phpMyAdmin" at position 0)
Unrecognized statement type. (near "SQL" at position 11)

#1064 - Something is wrong in your syntax obok 'phpMyAdmin SQL Dump
SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"' w linii 1

is there any SQL server based data source forms for updating a table

So essentially I want to create a form that is powered off of several sql server tables. Essentially the user inputs a single field and the rest of the form becomes populated off of the backend tables. From here the user submits the form and the information is stored in a seperate table. Is there any functions within SQL Server or Report builder that can accommodate this or am I going to have to have a web based solution for this?

How to update a column for two separated ids?

I have these two queries:

$dbh
->prepare("UPDATE user
            SET reputation = reputation - 15
            WHERE id = ?")
->execute(array($old_author));

$dbh
->prepare("UPDATE user
            SET reputation = reputation + 15
            WHERE id = ?")
->execute(array($new_author));

I want to know can I do that by one single query? I mean can I both - 15 and + 15 in reputation column for two users in the same query?

SQL Server Query to compare 2 select statements data

Can you please help me in combining the below 2 queries. The result should be as shown in attached image. I would like to compare the balance between 2 queries and flag the balance when state balance is less than city balance. select CT_ID, sum(balance) as StateBalance from tblApp where StateJurisdiction='New york' group by CT_ID order by CT_ID select CT_ID, sum(balance) as CityBalance from tblApp where StateJurisdiction in ('BRONX','BROOKLYN') group by CT_ID order by CT_ID

how to filter records that including null values and other status

Currently i am running below query in sql server. How to filter whose checkpointstatus is not 'Completed' including null values. But the issue is i am not able to get those records whose values are null

  SELECT * FROM TAMS.OrderDetail WHERE CheckPointStatus != 'Completed'

I have tried to fix this by

  SELECT * FROM TAMS.OrderDetail WHERE coalesce(CheckPointStatus, '') !=  'Completed'

But just want to make sure is this correct way

Select entire row as well as third highest salary

I need to fetch all row details of user with third highest salary.

My query

select min(salary)as minsalary from (select * from userdetails 
        order by salary desc limit 3) as details

Current output :-

Array
(
  [0] => stdClass Object
    (
        [minsalary] => 300
    )

)

i need to fetch the full row details too along with this array as single array output. How can i alter my query.

Please help.

mercredi 20 juillet 2016

Link three tables to on Foreign key

From this ERD could anyone tell me what the best way to connect the Modifier, Monster, and Equipment tables to the card table. I cannot just give have those tables have a FK of CardID because a Card may be the same Card, but have a different illustration, which would make the Card Unique but not the ModifierID, MonsterID, or EquipmentID. And I don't think you can have null foreign keys either. Is there any other way besides three more many to many tables?

How to remove a COMMA from a .txt file using an ANT script command

I have an ANT script and an SQL script. The ANT script makes the SQL script to run against the database and it generates a .txt file with multiple rows. The .txt file contains values like:

'value1',
'value2',
'value3',
 .
 .
'valueN',

I want to remove the COMMA in the last row. Is there any ANT command that I can use to make this happen?

I am new to both ANT and SQL

Skip certain tables with mysqldump

Is there a way to restrict certain tables from the mysqldump command?

For example, I'd use the following syntax to dump only table1 and table2:

mysqldump -u username -p database table1 table2 > database.sql

But is there a similar way to dump all the tables except table1 and table2? I haven't found anything in the mysqldump documentation, so is brute-force (specifying all the table names) the only way to go?

How to enable explicit_defaults_for_timestamp?

When I try to start my mySQL server I get message:

[Warning] TIMESTAMP with implicit DEFAULT value is deprecated. Please use --explicit_defaults_for_timestamp server option (see documentation for more details).

I find answer on:
http://dev.mysql.com/doc/refman/5.6/en/server-system-variables.html#sysvar_explicit_defaults_for_timestamp

But how enable it? Where?

MySQL for Each Value in Set [duplicate]

This question already has an answer here:

I have a SET column and have retrieved a value from it.

DECLARE types SET;
SET types = (SELECT...);

I'd like to iterate over types for each value of it.

How would I do this?

Heroic data tables

I am brand new to Heroku and am trying to get a sense of how it works for my application. My understanding is that calls to post and retrieve data from a database is through SQL data tables. I created a FREE database on Heroku and am trying to see a map of the data tables and they are nowhere to be found. How do Heroku databases work through data tables if we cannot see them?

Thank you for your help!

What to download from the MySQL site for a beginner on a MAC?

Help.

On the MySQL Downloads page, there are three edition options, Enterprise, Cluster, and Community. I assume I want to download from the Community section since I am not using, or learning for commercial purposes?

So then clicking on the Community downloads section, I have 11 options for MAC for download. Which ones do I need to get started? I want to learn MySQL/SQL at home and am just looking for the basics but am unsure what I need.

Is it possible to send push notification only to users who have the current install apk?

I have an Android apk, more than 200 people installed that apk so far, some people uninstalled this apk. Is it possible to mark in MYSQL which user has operational apk on his device? And then have system send push notifications only to those users who have operational apk.

please advise, user status:
enter image description here

Will exists clause compare the records?

I have two tables as

tb1(field1 int) containing 1,2,3,4
tb2(field2 int) containing 4,12,19,30

When I run

select * from tb1 where exists(select * from tb2 ); 

I'm getting the entire values from tb1. Why it's so? I thought that the it will bring only 4 as it is present in both tables. Now I'm totally confused with the exists clause. I want to know what the exists clause is doing here ? Please help me.

How to use if else in mysql where clause

I want to query data in mysql like:

$cid=$_POST["cid"];
$room_id=$_POST["room_id"];
$time=$_POST["time"];

$reuslt=$this->db-query("SELECT * FROM mytable WHERE if($cid is not null){then check cid=$cid} else{don't check} AND if($room_id is not null){then check room_id=$room_id} else{don't check} AND if($time is not null){then check time=$time} else{don't check}");

How could I writ the correct sql to query data?

I am getting an error saying "Overflow" in MS Access query when I try to use CDate

SELECT DISTINCT IWTUSER_ALARMS.NAME, IWTUSER_ALARMS.AID, IWTUSER_ALARMS.DUR, 
   Int(CInt([DUR])/86400) AS DAYS, Int((CInt([DUR]) Mod 86400)/3600) AS HOURS, 
   Int(((CInt([DUR]) Mod 86400) Mod 3600)/360) AS MINUTES, 
   Int((((CInt([DUR]) Mod 86400) Mod 3600) Mod 360)/60) AS SECONDS
FROM IWTUSER_ALARMS
   WHERE (((CDate(Format([IWTUSER_ALARMS].[ITIME],"0000-00-00 00:00:00 ")))>=Date()-10))
GROUP BY IWTUSER_ALARMS.NAME, IWTUSER_ALARMS.AID, IWTUSER_ALARMS.DUR, 
   CInt([DUR])/86400, CInt([DUR]) Mod 86400, (CInt([DUR]) Mod 86400) Mod 3600, 
   ((CInt([DUR]) Mod 86400) Mod 3600) Mod 360
ORDER BY IWTUSER_ALARMS.DUR DESC;

Using large data sets

I have created a table with just field names and I have the data saved to my computer but now want to code to input it into the table with currently only the field names. (it is a couple million records so going by columns doesn't seem to work)

  • I tried using an INSERT INTO new_table SELECT FROM original_table
  • I've also tried just copying and pasting the values into the script but it is too large

MYSQL Query Issue in Codeigniter

High friends,

could you please help me to check date from datetime on mysql query in codeigniter

like

return $this->db->select("*")->from($this->db->dbprefix."notification")->where('date',date('Y-m-d'))->get()->result();

in database date is in this format date('Y-m-d h:i:s'); i am also trying by using like it is not working for me please anybody help me

phpmyadmin enable drop database statement

I was alerted by my hosting provider that I exceed my 1000 table limit. I have a lot of databases and would like to delete more at once. Unfortunaltley they don't have a multiselect feature so I decided to use a query in phpmyadmin.

When I try something like DROP database some_name I get DROP DATABASE statements are disables

Does anyone know if it's possible to enable them or a different way to delete multiple databases?

Counting same data from several column values

i am using sql server 2014.

I have five columns for responses different question, however the different users can possible response the same for different questions.

Getting individual column counts I can do.But how can I get a total of same responses/values from the 5 columns.

Column A    Column B   Column C    Column D    Column E
x           x          y           z           aa
y           z          0           0           0
0           x          x           0           x
aa          bb         0           x           aa

etc

thanks

SQL Query , sorting out the data using column values, with conditions involved

I am new to Data analysis, and just starting out at my new job. The database is Oracle 11g and query tool i am using is SQL Developer. Any tips would be greatly appreciated. I have attached a link excel file as I couldn't make table here. I am having a hard time figuring out the logic for this one. Please have a look and Thank you in advance. enter image description here

SQL Export after 50 entries and then Delete the Table entries entirely

this is my first post. I have insert form using pdo, ajax and sql and I Want to after 100 entries export to csv in back up folder . And then purge the table of all information. I need help to understand how I can do this? I was thinking a trigger or event or maybe C# program to do this but i wanted opinions on all things security, functionality and different ideas to make this happen. I truly do appreciate any time spent considering my request. . . Thank you

How to remove all the non numeric characters from column in mysql in bulk data

I want to remove all the non numeric characters from the column. I have bulk data in my database.

Currently I am using method as describe in below link:

http://venerableagents.wordpress.com/2011/01/29/mysql-numeric-functions/

The problem is that its taking too much time for preocessing.

For 1 million of row current logic takes 1 hour to process the data.

please help me..

Thank You, Ronak

Mysql remote connections

I've an application on windows forms that needs to connect to a remote server with a static ip, however I already installed mysql on the server, provided the next command

     GRANT ALL PRIVILEGES ON *.* TO 'root'@'%' IDENTIFIED BY 'password' WITH GRANT OPTION; FLUSH PRIVILEGES;

and also put an exception in Windows Firewall, but I'm still unable to connect, I don't know if there is something else to do!, I forgot to say it is a Windows Server 2012 R2

how mysql deal with different type convert when using where clause

for example there is a type varchar(50) named by cardNo in table "bankcard",and it has a record,value is 6228480329288486759 when i query it as follows

SELECT id,cardNo  FROM BANKCARD WHERE cardNo = 6228480329288486000

it will find the record "6228480329288486759"

however,use clause like this

SELECT id,cardNo  FROM BANKCARD WHERE cardNo = "6228480329288486000"

the result dose not exist

i wonder how mysql deal with the the different type,convert numeric type to varchar

How can I store a dictionary in an Azure SQL Database? (Swift)

I want to store a dictionary in a column in an Azure SQL Database. I've tried to store a dictionary by doing :

let item = ["text":["foo":"bar"]]
    let itemTable = client.tableWithName("TodoItem")
    itemTable.insert(item) {
        (insertedItem, error) in
        if (error != nil) {
            print("Error" + error!.description);
        } else {
            print("Item: " String(insertedItem!))
        }
    }

But when I query the database I get

Item: [Object object]

How can I store and query dictionaries in the database without the items changing?