w3hello.com logo
Home PHP C# C++ Android Java Javascript Python IOS SQL HTML videos Categories
Logical "Except" operator for If statements in R
Something like this could work (in pseudocode becuase there is no data), ifelse(oneDayMatrix[i-1, 4] > 0, 'do the other thing you want it to do', ifelse(oneDayMatrix[i,10] == -180 & oneDayMatrix[i,4] == 0, {impute1 <- replace(oneDayMatrix[ ,10], oneDayMatrix[i,10], rowBefore) ctr <- (ctr + 1)}, print("No data fit this criteria.")))

Categories : R

Using Javascript if statements with and operator and selectors to create navigation bar
jsFiddle Demo You should probably do something more along these lines by taking advantage of jQuery's hover: $('#submenu').hide(); $('#portmenu, #first, #second, #third').hover(function(){ //in $('#submenu').show(); },function(){ //out $('#submenu').hide(); });

Categories : Javascript

Does Java run each conditional operator or does it short-circuit in If statements?
You're using & instead of &&. The former is bitwise AND and will evaluate both sides always. The latter stands for logical AND and will do short-circuit conditional evaluation. More info: Java Tutorials: Operators Solution for your current problem: use logical AND && instead of bitwise AND &. Similar for your bitwise OR |. if( !currentFragment.getTag().equals(PROFILE) || ( currentFragment.getArguments() != null && currentFragment.getArguments().getInt("authorId") != userId) ) { }

Categories : Java

mysql - Mix two statements
If both the queries are on the same table and all the conditions are OR you can directly do : SELECT * FROM inventory WHERE `pro_status`='1' or `pro_status`='2' OR `loca_city` = 'hk' or `loca_city` = 'tw' or `loca_city` = '

Categories : Mysql

if else statements in mysql where clause
I'd like to suggest a possible alternative which will greatly simplify, and possibly speed up (though you should measure this as with all optimisation claims), your queries. Consider assigning the default image to users when they join then simply allow them to override it. That way, every user has an image which can be extracted the exact same way regardless of whether they've configured one or not. And, unless you're planning on millions and millions of users, the space requirements shouldn't be onerous. You can still maintain a field in the table to state whether a real image has been chosen, even though that technically may violate 3NF. Most people don't realise but it's quite okay to do that sort of thing (usually for performance or simplification) provided you understand and/or mit

Categories : Mysql

MYSQL: Combine AVG and LIKE Statements into One
You should be able to use something like the following: SELECT b.name, AVG(m.rating) AS avgRating FROM beers b LEFT JOIN myBeers m ON b.beerID = m.beerID WHERE b.name LIKE '%Hocus%' GROUP BY b.name You do not need another query in your WHERE clause. This will check that the name of the beer is LIKE the string you are passing in. You just need to decide where you want the wildcard % on the LIKE. I have added it to both the start and end of Hocus but you might only need it on the end. Also, since you are using an aggregate function Avg() you need to use a GROUP BY clause. The GROUP BY should contain the other columns that are included in the select list. You will notice that I removed the select * ad replace it withe select b.name. Also if you want to return beers that do no

Categories : Mysql

Both mysql statements must be true
You just need another set of parentheses $sql ="SELECT products.name, products.sku, products.feedid, products.brand, products.merchant, map.merch, map.productid from products, map where (products.feedid != map.productid && products.merchant != map.merch) and (products.name LIKE '%" . $search . "%' or products.sku LIKE '%" . $search . "%' )";

Categories : PHP

Prepared Statements + MySQL (7 day Stats)
Try using PDO instead, it has some really cool features, like fetching data into multidimensional arrays with just a simple fetch; this is probably what you're looking for. Check this tutorial out: http://net.tutsplus.com/tutorials/php/why-you-should-be-using-phps-pdo-for-database-access/ I feel kind today and will provide you with some sample code: $sth = $dbh->prepare('SELECT `object_id`, `date`, `impressions`, `clicks` FROM `object_stats` WHERE `user_id` = ?'); $sth->execute(array($_SESSION['user_id'])); $data = $sth->fetchAll(PDO::FETCH_COLUMN | PDO::FETCH_GROUP);

Categories : PHP

Joining Multiple MySQL Statements
You can join them together into one query like this: select pl.*, avg(vote) as rating from (SELECT path, id FROM paths WHERE path = {path} ORDER BY created DESC LIMIT 1 ) p left outer join votes v on v.id = p.id left outer join places pl on pl.id = p.id group by p.id; EDIT: The first two conditions do seem redundant. But, if you need them: select pl.*, avg(vote) as rating from (SELECT path, id FROM paths WHERE id = (select id from paths where path = {path} order by created desc limit 1) ORDER BY created DESC LIMIT 1 ) p left outer join votes v on v.id = p.id left outer join places pl on pl.id = p.id group by p.id;

Categories : Mysql

Sql Statements as Data in mySQL Database
Storing SQL queries as data in a SQL DB is sometimes labelled dynamic SQL queries. It is prone to injection issues, and should not be undertaken lightly. I recommend not doing so unless you have a very good reason to do so.

Categories : Mysql

MySql how to union 2 queries within if statements
Just a suggestion, its ugly but simple : $teamsters = ''; $query = ''; if (isset($_POST['A'][0]) && !empty($_POST['A'][0])) { $query= "SELECT * FROM (SELECT * FROM myTable WHERE...) as A WHERE Column1='y'"; $teamsters = ' UNION '; } if (isset($_POST['B'][0]) && !empty($_POST['B'][0])) { $query .= $teamsters . "SELECT * FROM (SELECT * FROM myTable WHERE...) as B WHERE Column2='y'"; }

Categories : Mysql

Multiple simultaneous SELECT statements in MySQL
You should use transaction. Not on client app, but on server app. begin transaction update table1 set .... update table2 set .... update table2 set .... commit this way, table1 and table2 committed simultaneously, ensuring consistent read on client apps. Note: you have to use InnoDB engine for transaction to work

Categories : C#

Query to get all CREATE statements of MySql Tables
mysqldump -h localhost -u root -p --no-data --compact some_db mysqldump -d --compact --compatible=mysql323 ${dbname}|egrep -v "(^SET|^/*!)" How do I use mysqldump to export only the CREATE TABLE commands

Categories : Mysql

adding multiple do statements on a page using php and mysql
What happens if there is no row for staffID=81 change code to something like this, ..... do { $row_myContacts = mysql_fetch_assoc($myContacts); if ($row_myContacts == false){ break; } .....

Categories : PHP

The right mySQL syntax for multiple SELECT statements?
The first query also wont work. try this. SELECT AVG(salaryoffered) AS "Average Salary", MIN(salaryoffered) AS "Min Salary", MAX(salaryoffered) AS "Max Salary" FROM interview; If you want to add some text, use concat, something like SELECT concat(AVG(salaryoffered), "$ offered") AS "Average Salary", concat(MIN(salaryoffered), "$ offered") AS "Min Salary", concat(MAX(salaryoffered), "$ offered") AS "Max Salary" FROM interview;

Categories : Mysql

MySQL stored Procedure error with IF...THEN...END IF; statements
Change this line: ALTER TABLE test_schema.new_table CHANGE id AccountID VARCHAR; to this: ALTER TABLE test_schema.new_table CHANGE id AccountID VARCHAR(100); Of course you should specify a length for the VARCHAR column that is appropriate. I've just used VARCHAR(100) as an example.

Categories : Mysql

Are MySql Stored Procedures preferable to Prepared Statements?
In a lot of cases, the performance difference is negligible. The real performance savings using a stored procedure comes from reducing the number of round trips to the database, when the stored procedure is performing multiple SQL statements. If a stored procedure is wrapping a single SQL statement, and it's being called from the application in place of a single SQL statement, then it's unlikely there is any performance benefit with MySQL. (There may actually be a little more work for MySQL to do calling the stored procedure.) Where we usually get a performance boost with a stored procedure is reducing the number of statements executed by the client; that is, eliminating some of the statement "execute" calls.

Categories : Mysql

MySQL syntax issue, multiple SELECT statements
SELECT a.username, COUNT(b.by_user) totalCount, SUM(IFNULL(b.votes,0)) total_votes FROM users_fb a LEFT JOIN posts b ON a.id = b.by_user WHERE b.by_page = '0' GROUP BY a.id,a.username

Categories : Mysql

MySql / PHP tick marks in update query statements
It's the backtick operator and is used to escape words referring to field or table names that are reserved words in MySQL's dialect of SQL, or contain invalid characters such as spaces. So if you have a table called select, with a field called select, you'd have to retrieve it like this: select `select` from `select` The backticks allow MySQL to correctly parse this as a working query without getting confused on the meaning of the words. Official documentation is here.

Categories : PHP

Optimizing MySQL query with nested select statements?
This is an equivalent query using joins. It depends what indexes are defined on the tables how this will perform. If your Perl interface has the notion of prepared statements, you may be able to save some time by preparing once and executing with 9000 different binds. You could also possibly save time by building one query with a big acd.content_url_id In ($content_path_id1, $content_path_id2, ...) clause Select an.uuid From alf_node an Inner Join alf_node_properties anp On an.id = anp.node_id Inner Join alf_content_data acd On anp.long_value = acd.id Where acd.content_url_id = $content_path_id

Categories : Mysql

Running a script (multiple statements) using the Mysql gem in Ruby
Sending each statement separately is fine. They are unique in SQL because they are separated by semicolons (";"). You'll get an array of hashes if multiple rows match your query. You can iterate over them using each or map if you want to transform them. It's one of the most common things you'll do with database access from inside a language, whether it's Ruby, Python, Perl or Java. I highly recommend you look into using the Sequel gem as your interface to the database. It's an ORM, acting as a nice interface layer between your code and SQL and the DBM. You can write your queries programmatically, which is a big win. Instead of having to write SQL, you let Sequel generate the queries for you.From my experience, it does a very good job writing efficient code; You have to go out of your way

Categories : Mysql

Why am I not seeing any performance increase by implementing MySQL prepared statements?
I would use some sort of time functionality to determine the exact speed of your transactions. Such as: $time = -microtime(true); // run transactions $time += microtime(true); echo $time . ' in seconds to process...'; Also, prepared statements are not necessarily created to increase performance. If anything I would assume they would slow things down. Prepared statements are to 'prepare' statements. Meaning they process the text, quote any parameters to protect against SQL Injection and make sure that the SQL statement does not have any syntax errors. That overhead will not provide performance boosts.

Categories : PHP

Liquibase importing sql files for mysql fails on multiple statements
A bit more searching to figure out that the problem is not with Liquibase but with MySql driver that by default refuses to execute multiple statements. The key bit was to add allowMultiQueries=true to my connection string: url: jdbc:mysql://localhost/test_project?allowMultiQueries=true

Categories : Mysql

Mysql not returning result when using escaped slash using match statements
The problem is that very short words are not indexed, by default. Here is the documentation: The minimum and maximum lengths of words to be indexed are defined by the ft_min_word_len and ft_max_word_len system variables. (See Section 5.1.4, “Server System Variables”.) The default minimum value is four characters; the default maximum is version dependent. If you change either value, you must rebuild your FULLTEXT indexes. For example, if you want three-character words to be searchable, you can set the ft_min_word_len variable by putting the following lines in an option file: [mysqld] ft_min_word_len=3 This applies to boolean search as well as natural language. You will need to change the option an rebuild the index. Alternatively, you could put in a regexp express

Categories : PHP

Using php to loop through mysql table, why aren't elseif statements working?
The while statement will stop when no rows are available anymore. If you express an assignment in a while loop in PHP, the condition will be considered true as long as the variable is effective (not NULL). Otherwise the loop will end.

Categories : PHP

Convert List To Comma Separated MySQL Insert Statements
String.Join(",", models.Select(m => String.Format("({0},{1},{2})", m.ModelId, m.Name, m.Enabled))); That will give you string with False and True as Enabled values. If you want Enabled and Disabled instead, then use: m.Enabled ? "Enabled" : "Disabled" when formatting model string. Full sample (with NBuilder used to create sample models): IEnumerable<Model> models = Builder<Model>.CreateListOfSize(3).Build(); Func<Model, string> formatModel = m => String.Format("({0},{1},{2})", m.ModelId, m.Name, m.Enabled); string result = String.Join(",", models.Select(formatModel)); Output: (1,Name1,False),(2,Name2,True),(3,Name3,False)

Categories : C#

MySql SELECT with some AND operator
It needs to be OR but you've misspelt touch. You have also stated that you want the result to be 34, 45 but your query is searching for 27 and 20. You could use SELECT DISTINCT prod_id rather than GROUP BY but it is not a big deal.

Categories : Mysql

Do MySQL transactional queries improve performance for multiple SELECT statements?
Transactions can give big boost for INSERT/UPDATE/DELETE queries (provided that you use transactional engine like InnoDB), but on SELECT only queries, using transactions are NOT likely to improve performance (but may be still needed by your application logic to ensure consistency). Main reason for speed difference: if you do not use transactions, server must flush every single update to disk as soon as possible, to make sure that data will survive should server crash or lose power. With transactions, server only needs to guarantee that all updates batched in one transactions are committed to disk, or the whole thing is rolled back. In other words, server is free to group many writes into few disk operations, and only needs to commit transaction when it is absolutely sure that data is safe

Categories : PHP

MySQL efficiency - do repeated statements in one query get executed multiple times?
Try to compare the execution times between: SELECT AVG(var1) AS var1_average, AVG(var2) AS var2_average, ( AVG(var1) + AVG(var2) )/2.0 AS total_average FROM readings And: SELECT (var1_average+var2_average)/2.0 AS total_average var1_average, var2_average FROM ( SELECT AVG(var1) AS var1_average, AVG(var2) AS var2_average FROM readings ) as tmp Make sure to run them multiple times and also add SQL_NO_CACHE to get meaningful results. NOTE: The second query should have a small overhead since mysql will create a temp table but this will be irrelevant if there are a lot of records in readings table.

Categories : Mysql

How to create sql script that generates insert statements with tables data in mysql/mssql
If you want to insert the existing data again into your table (as you have mentioned in the question) then, you can write an sql like: INSERT INTO country (NAME) SELECT NAME FROM COUNTRY;

Categories : Mysql

Filtering MySQL query. "AND" operator
My guess is you need to do two comparisons like this: SELECT * FROM pl_tab WHERE pal_num in (".$weights.") AND lt_num in (".$weights."); You can't say column1 and column2 = 3 for example. If you want rows where both are equal to 3, you would need to use column1=3 and column2=3 in your query. Also, you might want to have a read of this Q&A that I wrote a while back which covers off a lot of basic SQL queries and expands from there. Edit: If you have $weights in the query, you do set it somewhere, or do you want it to be what is in your variables you show here: $weights = $_POST['pal_num']; $weights = "'".implode("','",$_POST['pal_num'])."'"; Is this what you meant?

Categories : PHP

MySQL UNION operator error in PHP
Your SELECT clause has no aliases mentioned. As a result, SQL engine does not know what column names to generate. I am assuming it takes the column names of the 1st SELECT. Hence you see undefined index for "Receiver" which is a part of 2nd SELECT. Also, I do not understand the logic behind the UNION. You are trying to UNION results of 3 different tables that have completely different columns.

Categories : PHP

Php and mysql wildcard operator when searching a database
Only way you could probably do is to with either a regex or white space replacement. PHP: $term = str_replace(' ', '', $_POST["search term"]); Query: Select * from customer where REPLACE(postcode, ' ', '') LIKE '%".$term."%' Having said that however, you'd be far better off formatting the data on insert, because as your table grows, that lookup will become more and more expensive to run. One of my pet hates is websites that use a post code as authentication or verification data, then force you to use a particular notation. I've seen people hypenate the space in their post code before too, so you should always normalise the format before inserting it, or enforce a format (i prefer the former option, but the latter is easier). Also your query is vulnerable to injection exploits. But th

Categories : PHP

MYSQL <= operator not working for values of 9999
Can you post your full query as its not clear what is SSR and FD and also some sample data. Is it possible(pretty sure) that the minScore and MaxScore you are getting from SPP might not be as per your expectation because of some other conditions in the where clause

Categories : Mysql

MySQL query not working after adding AND operator
Try this: $result = mysql_query("SELECT * FROM pl_table WHERE p_num='". $w[0]."' AND l_num='".$w[0]."'" ); Basically, you messed up w/ opening/closing quotes. What error message did PHP return to you? Most of the times, if not always your solution lies therein.

Categories : PHP

100% CPU USAGE: MySQL 2,000,000 rows and query with LIKE operator
Well, one solution would be to stop using a performance killer like like '%something%'. One way we've done this in the past is to maintain our own lookup tables. By that I mean, put together insert, update and delete triggers which apply any changes to a table like: word varchar(20) id int references mp3list(id) primary key (word,id) Whenever you make a change to mp3list, it gets reflected to that table, which should be a lot faster to search than your current solution. This moves the cost of figuring out what MP3s contain what words to when you update, rather than every time you select, amortising the cost. Since the vast majority of databases are read far more often than written, this can give substantial improvements. Some DBMS' provide this functionality with a full te

Categories : PHP

How to use assignment operator in mysql stored procedore
Try changing : SELECT sp_ApplicationId = ApplicationId FROM aspnet_Applications WHERE LOWER(sp_ApplicationName) = LoweredApplicationName to: SELECT 1 FROM aspnet_Applications WHERE LOWER(sp_ApplicationName) = LoweredApplicationName UPDATE if you are trying to assign the value of ApplicationId to sp_ApplicationId variable you can try: SELECT ApplicationId INTO sp_ApplicationId FROM aspnet_Applications WHERE LOWER(sp_ApplicationName) = LoweredApplicationName

Categories : PHP

MySQL performance differences between a different "FROM" operator usage
This is speculation (my powers of reading MySQL explain output are weaker than they should be, because I want to see data flow diagrams). But here is what I think is happening. The first query is saying "Let's go through B and look up the appropriate value in A". It then looks up the appropriate value using the id index, then it needs to fetch the page and compare to name. These accesses are inefficient, because they are not sequential. The second version appears to recognize the condition on name as being important. It is going through the name index on A and only fetching the matching rows as needed. This is faster, because the data is in the index and few pages are needed for the matching names. The match to B is then pretty simple, with only one row to match. I am surprised at

Categories : Mysql

MySQL: Possible to apply the OR operator across multiple selected rows?
One way to solve this is if you use values 0 and 1 as role permissions. And use some query like: SELECT u.name, SUM(r.basement_access) AS basement_access, SUM(r.user_directory_access) AS user_directory_access FROM users u LEFT JOIN positions p ON u.userId=p.userId LEFT JOIN roles r ON r.roleId=p.roleId WHERE u.userId=123 GROUP BY u.userId;

Categories : Mysql

mysql-connector python 'IN' operator stored as list
I'm not familiar with mysql-connector, but its behavior appears to be similar to MySQLdb in this regard. If that's true, you need to use a bit of string formatting: sql = """SELECT avg(downloadtime) FROM tb_npp where date(date) = %s and substring(host,6,3) in ({c})""".format( c=', '.join(['%s']*len(dc))) args = ['2013-07-01'] + dc cursor3.execute(sql, args)

Categories : Python



© Copyright 2017 w3hello.com Publishing Limited. All rights reserved.