all rows in table have type field. It is either 0 or 1.
I need to count rows with 0 and with 1 in one query. So that result is something like:
type0 type1
1234 4211
How it can be implemented?
Right now I have the following query:
SELECT name, COUNT(name), time, price, ip, SUM(price) FROM tablename WHERE time >= $yesterday AND time <$today GROUP BY name
And what I'd like to do is add a DISTINCT by column 'ip', i.e.
SELECT DISTINCT ip FROM tablename
So my final output would be all the columns, from all the rows that where time is today, grouped by name (with name count for each repeating name) and no duplicate ip addresses.
What should my query look like? (or alternatively, how can I add the missing filter to the output with php)?
Thanks in advance.
Hi guys,
I've got this code
mysqli_query ( $userdatabase,
'CREATE TABLE `user_'.$emailreg.'` (
ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,
IP varchar(10),
FLD1 varchar(20),
FLD2 varchar(40),
FLD3 varchar(25),
FLD4 varchar(25),
FLD5 varchar(25) )' );
echo ( mysqli_error ($userdatabase) );
that works fine on my localhost, but when I upload it to the server, it starts giving me a "Incorrect table name '[email protected]'" error. any idea?
Thanks!
is there any way to avoid using tmp table?
I am using a query with aggregate function (sum) to generate the sum of each product: the result looks like this:
product_name | sum(qty)
product_1 | 100
product_2 | 200
product_5 | 300
now i want to join the above result to another table called products. so that i will have a summary like this:
product_name | sum(qty)
product_1 | 100
product_2 | 200
product_3 | 0
product_4 | 0
product_5 | 300
i know 1 way of doing this is the dump the 1st query result to a temp table then join it with products table. is there a better way?
I've got 3 tables that are something like this (simplified here ofc):
users
user_id
user_name
info
info_id
user_id
rate
contacts
contact_id
user_id
contact_data
users has a one-to-one relationship with info, although info doesn't always have a related entry.
users has a one-to-many relationship with contacts, although contacts doesn't always have related entries.
I know I can grab the proper 'users' + 'info' with a left join, is there a way to get all the data I want at once?
For example, one returned record might be:
user_id: 5
user_name: tom
info_id: 1
rate: 25.00
contact_id: 7
contact_data: 555-1212
contact_id: 8
contact_data: 555-1315
contact_id: 9
contact_data: 555-5511
Is this possible with a single query? Or must I use multiple?
Hi guys.
I've accidentally dropped a database inside my server .
I have no backup of it and binary logs are not enabled (shame on me!) ...
Is there any way to restore that db?
I'm trying to write an SQL statement that will generate an SQL script that will update a BLOB field with an IMAGE being selected from the database.
This is what I have:
select concat( 'UPDATE `IMAGE` SET THUMBNAIL = ',
QUOTE( THUMBNAIL ),
' WHERE ID = ', ID, ';' ) as UPDATE_STATEMENT
from IMAGE;
In the above, THUMBNAIL is a BLOB field containing raw image data. When I run the resulting script I get the following error:
ERROR at line 2: Unknown command '\\'.
I first tried this without the QUOTE() function, like so:
select concat( 'UPDATE `IMAGE` SET THUMBNAIL = \'',
THUMBNAIL,
'\' WHERE ID = ', ID, ';' ) as UPDATE_STATEMENT
from IMAGE;
Running the resulting script produces this error:
ERROR at line 2: Unknown command '\0'.
What is the proper function to apply to this BLOB field in the select, so the UPDATE statements will work?
If context is required, I'm looking to migrate thumbnails generated on one server to another server for certain image IDs only. I would use mysqldump, but I don't want to clobber the entire table.
Any help is greatly appreciated!
I want to know whether the PHP serialize function is 100% secure, also if we store serialized data into a database and want to do something after fetching it, will it be a nice way.
For example:- I have a website with different user privileges, now i want to store the permissions settings for a particular privilege to my database (This data i want to store is to be done through php serialize function), now when a user logs in i want to fetch this data and set the privilege for the customer.
Now i am ok to do this thing, what i want to know is, whether it is the best way to do or something more efficient can be done.
Also, i was going through php manual and found this code, can anybody explain me a bit what's happening in this code:- [Specially why base64_encode is used?]
<?php
mySerialize( $obj ) {
return base64_encode(gzcompress(serialize($obj)));
}
myUnserialize( $txt ) {
return unserialize(gzuncompress(base64_decode($txt)));
}
?>
Also if somebody can provide me their own code to show me to do this thing in the most efficient manner.
Thanks.
Hello,
How can I query data from a table available on a list of strings?
I only want to get the data from the list of strings.
Example:
Table
ID Name
1 Big
2 Small
3 Extra
4 Orange
5 Drink
List of Strings:
Big
Small
Extra
Thanks!
Hi,
Lets say I am analyzing how high school sports records affect school attendance.
So I have a table in which each row corresponds to a high school basketball game. Each game has an away team id and a home team id (FK to another "team table") and a home score and an away score and a date. I am writing a query that matches attendance with this seasons basketball games.
My sample output will be (#_students_missed_class, day_of_game, home_team, away_team, home_team_wins_this_season, away_team_wins_this_season)
I now want to add how each team did the previous season to my analysis. Well, I have their previous season stored in the game table but i should be able to accomplish that with a subselect.
So in my main select statement I add the subselect:
SELECT COUNT(*) FROM game_table
WHERE game_table.date
BETWEEN 'start of previous season' AND 'end of previous season'
AND (
(game_table.home_team = team_table.id
AND game_table.home_score > game_table.away_score)
OR (game_table.away_team = team_table.id
AND game_table.away_score > game_table.home_score))
In this case team-table.id refers to the id of the home_team so I now have all their wins calculated from the previous year.
This method of calculation is neither time nor resource intensive. The Explain SQL shows that I have ALL in the Type field and I am not using a Key and the query times out. I'm not sure how I can accomplish a more efficient query with a subselect. It seems proposterously inefficient to have to write 4 of these queries (for home wins, home losses, away wins, away losses).
I am sure this could be more lucid. I'll absolutely add color tomorrow if anyone has questions
I have two tables that were built for two disparate systems. I have records in one table (called "leads") that represent customers, and records in another table (called "manager") that are the exact same customers but "manager" uses different fields
(For example, "leads" contains an email address, and "manager" contains two fields for two different emails--either of which might be the email from "leads").
So, I've created a correlation table that contains the lead_id and manager_id. currently this correlation table is empty.
I'm trying to query the "leads" table to give me records that match either "manager" email field with the single "leads" email field, while at the same time ignoring fields that have already been added to the "correlated" table. (this way I can see how many leads that match have not yet been correlated.) Here's my current, invalid SQL attempt:
SELECT leads.id, manager.id
FROM leads, manager
LEFT OUTER JOIN correlation ON correlation.lead_id = leads.id
WHERE correlation.id IS NULL
AND leads.project != "someproject"
AND (manager.orig_email = leads.email OR manager.dest_email = leads.email)
AND leads.created BETWEEN '1999-01-01 00:00:00' AND '2010-05-10 23:59:59'
ORDER BY leads.created ASC;
I get the error: Unknown column 'leads.id' in 'on clause'
Before you wonder: there are records in the "leads" table where leads.project != "someproject" and leads.created falls between those dates. I've included those additional parameters for completeness.
Hi guys,
I have a database with date field is this format "2010.06.11. | 10:26 13"
What is need is a php array that would hold all the different dates, .i.e.
array[0] = "2010.06.09."
array[1] = "2010.06.10."
array[2] = "2010.06.11."
Currently I am doing it by selecting the whole table, then looping through the result and adding the date substr to an array if it is not already there.
But maybe there is a faster way? Thanks.
I have some PHP code which stores whatever is typed in a textbox in the databse. If I type in bob's apples, it gets stored in the database as bob's apples.
What can be the problem?
The table storing this has the collation of latin1_swedish_ci.
I asked this last week over the weekend and it got buried in the archives before anyone could answer. So forgive me if you've already seen this.
I teach classes and want to be able to select those students who have taken one class, but not another class. I have two tables: lessons_slots which is the table for every class such as:
--------------------
-ID name slots-
-1 basics 10 -
-2 advanced 10 -
-3 basics 10 -
---------------------
The other table is class_roll, which holds enrollment info, such as:
--------------------
-sID classid firstname lastname-
-1 1 Jo Schmo
-2 1 Person Two
...
-13 2 Jo Schmo
---------------------
What I want to do, I select everyone who has not had the advanced class (for example). I've tried doing
SELECT *
FROM lessons_slots
LEFT JOIN class_roll
ON lessons_slots.ID = class_roll.classid
WHERE lessons_slots.name != 'advanced'
But that doesn't work...All it does is eliminate that row, without eliminating the user. I want Jo Schmo, for example, to not show up in the results. Any ideas?
I am trying to group a number of customers together based on their "Head Office" or "Parent" location.
THis works ok except for a flaw which I didn't forsee when I was developing my system... For customers that did not have a "Parent" (standalone business) I defaulted the parent_id to 0. Therefore, my data would look like this:
id parent_id customer
1 0 CustName#1
2 4 CustName#2 - Melbourne
3 4 CustName#2 - Sydney
4 0 CustName#2 (Head Office)
What I want to do is Group my results together so that I have one row for CustName#1 and one row for CustName#2 BUT my problem is that there is no parent record for parent_id=0 and these rows are being excluded when using an inner join.
I've tried using a case statement but that is not working either (parents are still being ignored)
Any help would be greatly appreciated.
Here is my query (My CASE is basically trying to get the business_name from the customer table based on the parent_id EXCEPT when the parent_id = 0, THEN just use the customer_name that is listed in the job_summary table):
SELECT
js.month_of_year,
(CASE js.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) as customer,
SUM(js.jobs),
SUM(js.total_cost),
sum(js.total_sell)
FROM JOB_SUMMARY js INNER JOIN
customer c on js.parent_id=c.id
group by
js.month_of_year,
(CASE c.parent_id WHEN 0 THEN js.customer_name ELSE c.business_name END) ORDER BY `customer` ASC
I have a simple table made up of two columns: col_A and col_B.
The primary key is defined over both.
I need to update some rows and assign to col_A values that may generate duplicates, for example:
UPDATE `table` SET `col_A` = 66 WHERE `col_B` = 70
This statement sometimes yields a duplicate key error.
I don't want to simply ignore the error with UPDATE IGNORE, because then the rows that generate the error would remain unchanged. Instead, I want them to be deleted when they would conflict with another row after they have been updated
I'd like to write something like:
UPDATE `table` SET `col_A` = 66 WHERE `col_B` = 70 ON DUPLICATE KEY REPLACE
which unfortunately isn't legal in SQL, so I need help finding another way around.
Also, I'm using PHP and could consider a hybrid solution (i.e. part query part php code), but keep in mind that I have to perform this updating operation many millions of times.
thanks for your attention,
Silvio
Reminder: UPDATE's syntax has problems with joins with the same table that is being updated
Hi everybody....
I am trying to query a database to find the following
If a customer searches for a hotel in a city between dates A and B, find and return the hotels in which rooms are free between the two dates.
There will be more than one room in each room type(i.e. 5 Rooms in type A, 10 rooms in Type B etc) and we have to query the db to find only those hotels in which there is atleast one room free in atleast one type.
This is my table structure....
**Structure for table 'reservations'**
reservation_id
hotel_id
room_id
customer_id
payment_id
no_of_rooms
check_in_date
check_out_date
reservation_date
**Structure for table 'hotels'**
hotel_id
hotel_name
hotel_description
hotel_address
hotel_location
hotel_country
hotel_city
hotel_type
hotel_stars
hotel_image
hotel_deleted
**Structure for table 'rooms'**
room_id
hotel_id
room_name
max_persons
total_rooms
room_price
room_image
agent_commision
room_facilities
service_tax
vat
city_tax
room_description
room_deleted
And this is my query
$city_search = '15';
$check_in_date = '29-03-2010';
$check_out_date = '31-03-2010';
$dateFormat_check_in = "DATE_FORMAT('$reservations.check_in_date','%d-%m-%Y')";
$dateFormat_check_out = "DATE_FORMAT('$reservations.check_out_date','%d-%m-%Y')";
$dateCheck = "$dateFormat_check_in >= '$check_in_date' AND $dateFormat_check_out <= '$check_out_date'";
$query = "SELECT $rooms.room_id,
$rooms.room_name,
$rooms.max_persons,
$rooms.room_price,
$hotels.hotel_id,
$hotels.hotel_name,
$hotels.hotel_stars,
$hotels.hotel_type
FROM $hotels,$rooms,$reservations
WHERE $hotels.hotel_city = '$city_search'
AND $hotels.hotel_id = $rooms.hotel_id
AND $hotels.hotel_deleted = '0'
AND $rooms.room_deleted = '0'
AND $rooms.total_rooms - (SELECT SUM($reservations.no_of_rooms) as tot
FROM $reservations
WHERE $dateCheck
GROUP BY $reservations.room_id) > '0'";
The number of rooms already reserved in each room type in each hotel will be stored in the reservations table...
The thing is the query doesn't return any result at all...even though it should if i calculate it myself manually...
I tried running the sub-query alone and i don't get any result... And i have lost quite some amount of hair trying to de-bug this query from yesterday... What's wrong with this...? Or is there a better way to do what i mentioned above...?
Thanks for your time...
Edit : Code edited to remove an bud... thanks to
Hello,
I have read that in a case where a table has many columns, but most of the time only one of them is used (say a title column in a forum post), a way to increase performance would be a partition to two tables, where one will contain only the title and the other one will contain the other columns (such as the forum post body).
However, in case I use
select ForumTitle from Forum;
won't that be good enough to prevent the load of all columns (such as the forum post's body) to the memory, and eliminate the need of partition?
Thanks,
Joel
Hello,
Let's say I have a row:
???????
Someone enters as a query:
??
Should I break up the characters in the query, and individually perform a LIKE % % match on each character against the row, or is there any easier way to get a row that contains one of the two characters? FULLTEXT won't work with CJK characters.
Thanks!
Right now I am fetching all of the rows from one of my tables:
query = "SELECT * FROM thread WHERE threadid = 2 ORDER BY threadid DESC";
$result = mysql_query($query);
$num_rows = mysql_num_rows($result);
if((!is_bool($result) || $result) && $num_rows) {
while($row = mysql_fetch_array($result))
{
$thread = $row['title'];
$threadID = $row['threadid'];
$poster = $row['postusername'];
}
What I want to do is go to another table on my database: "post_display", and get the row 'text' where the threadid = 2.
Hai guys,
I have two tables Incharge and property. My property table has three fields 1stIncharge,2ndIncharge and 3rdIncharge. InchargeId is set as foreign key for all the above fields in the property table..
How to write a select statement that joins both the table.. I ve tried a bit but no result
select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I.Id from
Property as P join Incharge as I where (\\How to give condition here \\)
Guys 3 fields P.1stIncharge, P.2ndIncharge, P.3rdIncharge has foreign key I.Id
Edit:
select P.Id,P.Name,P.1stIncharge,P.2ndIncharge,P.3rdIncharge,I1.Id from
Property as P
inner join Incharge as I1 on I1.Id=P.1stIncharge
inner join Incharge as I2 on I2.Id=P.2ndIncharge
inner join Incharge as I3 on I3.Id=P.3rdIncharge
and this query working
Hi there,
In my database I have a lot of users who've misspelled their e-mail address. This in turn causes my postfix to bounce a lot of mails when sending the newsletter.
Forms include (but are not limited to) "yaho.com", "yahho .com" etc.
Very annoying!
So i have been trying to update those record to the correct value.
After executing select email from users where email like '%@yaho%' and email not like '%yahoo%'; and getting the list, I'm stuck because I do not know how to update only the yaho part. I need the username to be left intact.
So I thought I would just dump the database and use vim to replace, but I cannot escape the @ symbol..
BTW, how do I select all email addresses written in CAPS? select upper(email) from users; would just transform everything into CAPS, whereas I just needed to find out the already-written-in-CAPS mails.
Here is the procedure I wrote- Cursors c1 & c2. c2 is inside c1, I tried declaring c2 below c1 (outside the c1 cursor) but then I is NOT taking the updated value :( Any suggestions to make it working would be helpful, Thanks
create table t1(i int);
create table t2(i int, j int);
insert into t1(i) values(1), (2), (3), (4), (5);
insert into t2(i, j) values(1, 6), (2, 7), (3, 8), (4, 9), (5, 10);
delimiter $
CREATE PROCEDURE p1()
BEGIN
DECLARE I INT;
DECLARE J INT;
DECLARE done INT DEFAULT 0;
DECLARE c1 CURSOR FOR SELECT i FROM t1;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN c1;
REPEAT
FETCH c1 INTO I;
IF NOT done THEN
select I;
DECLARE c2 CURSOR FOR
SELECT j FROM t2 WHERE i = I;
OPEN c2;
REPEAT
FETCH c2 into J;
IF NOT done THEN
SELECT J;
END IF;
UNTIL done END REPEAT;
CLOSE c2;
set done = 0;
END IF;
UNTIL done END REPEAT;
CLOSE c1;
END$
delimiter ;
I've been trying left joins but as there are 2 joins, i think the problem is the 2nd join roots from table_B not table_A. i am not getting any results where there is the required data in the db. I am not getting a query error
the query (simplified)
SELECT events.*, ven.*, events_genres.*
FROM events
LEFT JOIN ven //OPTIONAL JOIN
ON events.ven_id = ven.ven_id //OPTIONAL JOIN
LEFT JOIN events_genres //REQUIRED JOIN
ON events.event_id = events_genres.event_id //REQUIRED JOIN
WHERE events.date >= '$this->now'
AND
WHERE events_genres.g_id = $g_id //REQUIRED MATCH
ORDER BY date
ven = optional, i'll have the info if its there.
events_genres = required, i dont want any results that do not have a genre
The table that contains information about members has a structure like:
id | fname | pic | status
--------------------------------------------------
1 | john | a.jpg | 1
2 | mike | b.jpg | 1
3 | any | c.jpg | 1
4 | jacky | d.jpg | 1
Table for list of friends looks like:
myid | date | user
-------------------------------
1 | 01-01-2011 | 4
2 | 04-01-2011 | 3
I want to make a query that will as result print users from "friendlist" table that contains photos and names of that users from "members" table of both, myid (those who adding) and user (those who are added).
That table in this example will look like:
myid | myidname | myidpic | user | username | userpic | status
-----------------------------------------------------------------------------------
1 | john | a.jpg | 4 | jacky | d.jpg | 1
2 | mike | b.jpg | 3 | any | c.jpg | 1