suppose i have a field with counts and when I get some updated counts I want to delete the fields where the count went down
$query = "DELETE FROM $table
WHERE id='$id' AND ($count-count)<0;";
how would i do something like this (I don't think this works)
It's hard to tell without more information, but this seems typical:
$query = "DELETE FROM $table WHERE count < $count";
Related
I have a SQL query
var sql = "Select * From Foo Where Bar = {0}"
I want to execute this using Entity Framework, but I want to impose an extra restriction, to see if column Id is in a certain range:
List<int> ids = ...;
var MyFoos = context.Foos.SqlQuery<Foo>(sql).Where(x => ids.Contains(x.Id));
Is this likely to result in efficient selection from the database, or would it end up executing the whole of "Select * From Foo Where Bar = {0}" first and only then filtering for the IDs?
The SQL statement in sql will be executed database side, and results will be returned to the client.
The filter .Where(x => ids.Contains(x.Id)); will then be executed against the results of your sql query, client side.
The .Where will not be translated to SQL.
I verified this using SQL Profiler on a similar query.
I'm trying to translate a SQL Statement into Propel, without so much success. I have this SQL Statement:
SELECT id, param1, param2
FROM Field1
WHERE id
in
(
SELECT DISTINCT Field1_id
FROM Field2
WHERE id in
(
SELECT DISTINCT `Field2_id`
FROM `Field3`
WHERE
`param7` is null
AND param5 > 40
)
) LIMIT 0, 1000
i started doing it in a raw Way:
$connection = Propel::getConnection();
$query = "my Query";
$statement = $connection->prepare($query);
$statement->execute();
$results = $statement->fetch(PDO::FETCH_ASSOC);
This works pretty well, but i can't do any Propel Actions on $results cause it is an Array.
So how can i translate this SQL into Propel without the raw Way?
A good quick-fix for this is to create a view in your database, and set up a read-only table in Propel for that view. You can then use your view model just as you would an ordinary Propel table. Now of course this is cheating, and is frowned upon by ORM purists, but it will get you going in the short term.
My approach is to try to refactor back to tables where I've used this for a trivial query, but for big, central queries (in particular complex queries that are used for primary drill-down screens) I've been more than happy to keep the view approach permanently.
As far as I know, Propel does not handle nested queries. Instead, you can write table subqueries.
I have two tables in mySQL, notably accounts and subscriber_data.
I want to use two columns present in the accounts table (id, name), and insert it to the subscriber_data table in two columns called (sub_id, value).
I cannot seem to find a way to retrieve this information and put it into the other table without it being bunched up in the same value field in the same row like this: 0, 0, 1
Currently, my PHP looks like this:
$sql = "SELECT * FROM accounts";
$result = mysql_query($sql);
while($alt_result = mysql_fetch_array($result, MYSQL_NUM)){
$id[] = $alt_result[0];
$value1[] = $alt_result[1];
}
$idstring = implode(', ', $id);
$value1 = implode(', ', $value1);
$sql = "INSERT INTO subscriber_data (field_id, sub_id, value) VALUES('1', '$idstring', '$value1') ON DUPLICATE KEY UPDATE value='$value1'";
$result = mysql_query($sql);
I am a novice at this, and obviously doing something wrong... I searched and couldn't find an answer.
Thanks.
I didn't see at first what you were doing in PHP before calling the insert script. Maybe because I'm not used to PHP scripting, though more probably because I didn't pay enough attention at the time.
So, as far as I can understand what you are doing, you seem to be doing it wrong way.
If you need to insert values from one table into another table, you just use the INSERT...SELECT construct.
In your case it should possibly be something like this:
INSERT INTO subscriber_data (field_id, sub_id, value)
SELECT '1', id, name
FROM accounts
Note that this is one instruction, and it replaces both SELECT... and INSERT... in your code. I think it will be enough if you leave only the last two lines of your PHP script above, where the SQL script you are storing to $sql should simply be modified according to my suggestion.
If I'm missing something, please let me know.
While going through some SQL books I found that examples tend to use question marks (?) in their queries. What does it represent?
What you are seeing is a parameterized query. They are frequently used when executing dynamic SQL from a program.
For example, instead of writing this (note: pseudocode):
ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = 7")
result = cmd.Execute()
You write this:
ODBCCommand cmd = new ODBCCommand("SELECT thingA FROM tableA WHERE thingB = ?")
cmd.Parameters.Add(7)
result = cmd.Execute()
This has many advantages, as is probably obvious. One of the most important: the library functions which parse your parameters are clever, and ensure that strings are escaped properly. For example, if you write this:
string s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE (name = '" + s + "')"
cmd.Execute()
What happens when the user enters this?
Robert'); DROP TABLE students; --
(Answer is here)
Write this instead:
s = getStudentName()
cmd.CommandText = "SELECT * FROM students WHERE name = ?"
cmd.Parameters.Add(s)
cmd.Execute()
Then the library will sanitize the input, producing this:
"SELECT * FROM students where name = 'Robert''); DROP TABLE students; --'"
Not all DBMS's use ?. MS SQL uses named parameters, which I consider a huge improvement:
cmd.Text = "SELECT thingA FROM tableA WHERE thingB = #varname"
cmd.Parameters.AddWithValue("#varname", 7)
result = cmd.Execute()
The ? is an unnamed parameter which can be filled in by a program running the query to avoid SQL injection.
The ? is to allow Parameterized Query. These parameterized query is to allow type-specific value when replacing the ? with their respective value.
That's all to it.
There are several reasons why it's good practice to use Parameterized Queries. In essence, it's easier to read and debug, and circumvents SQL injection attacks.
It's a parameter. You can specify it when executing query.
I don't think that has any meaning in SQL. You might be looking at Prepared Statements in JDBC or something. In that case, the question marks are placeholders for parameters to the statement.
It normally represents a parameter to be supplied by client.
I am using PHP and MySQL. In my program there is a select query involving joins. When I run it on localhost it's working fine but when I upload it on my server and try to execute it then it generates the following error:
The SELECT would examine more than MAX_JOIN_SIZE rows; check your WHERE and use SET SQL_BIG_SELECTS=1 or SET SQL_MAX_JOIN_SIZE=# if the SELECT is okay
How can I correct this?
When using PHP, SQL_BIG_SELECTS=1 should be set in a separate query before your main query. For example:
$mysqli = new mysqli("localhost", "root", "password", "db");
$mysqli->query("SET SQL_BIG_SELECTS=1"); //Set it before your main query
$results = $mysqli->query("SELECT a, b, c FROM test");
while($row = $results->fetch_assoc()){
echo '<pre>';
print_r ($row);
echo '</pre>';
}
Try running as a query previous executing your select:
SET SQL_BIG_SELECTS=1
Is this really executing over a huge dataset? If not this should be solved in a different way.
The parameter's effect is documented at http://dev.mysql.com/doc/refman/5.0/en/server-system-variables.html#sysvar_max_join_size.
You should filter the involved records more strictly (so there are less records involved in each part of the query). If possible start with the table where you can filter out the most records with a simple WHERE-clause.
I've ran into the same problem. Its a drupal site so no surprise that it fell over.
It was an old style query, ie Select blah From table1, table2, table3 Where table1.id=table2.id And table2.some = 'thing'
Like #VolkerK says, the solution was to move the where clauses that filtered table2 results before that which matched table1 to table2 (effectively the join clauses), thus decreasing the amount of records needing to match in table2 to table1.
For me the solution was to add an index key to all the columns the joins used to match.
If you are using PDO driver, set the PDO::MYSQL_ATTR_INIT_COMMAND in your driver_options array when constructing a new database handle
like so:
$dbh = new PDO('mysql:host=xxx;port=xxx;dbname=xxx', 'xxx', 'xxx', array(PDO::MYSQL_ATTR_INIT_COMMAND => 'SET SESSION SQL_BIG_SELECTS=1'));